Lock:
Lock
多线程和多进程最大的不同在于,多进程中,同一个变量,各自有一份拷贝存在于每个进程中,互不影响,而多线程中,所有变量都由所有线程共享,所以,任何一个变量都可以被任何一个线程修改,
因此,线程之间共享数据最大的危险在于多个线程同时改一个变量,把内容给改乱了
#coding=utf-8
import time, threading
# 假定这是你的银行存款:
balance = 0
def change_it(n):
# 先存后取,结果应该为0:
global balance
balance = balance + n
balance = balance - n
print balance
def run_thread(n):
for i in range(100000):
change_it(n)
threads = []
t1 = threading.Thread(target=run_thread,name='xxyy11', args=(5,))
threads.append(t1)
t2 = threading.Thread(target=run_thread,name='xxyy22', args=(8,))
threads.append(t2)
for t in threads:
t.start()
t.join()
print 'thread %s ended.' % threading.current_thread().name
00
00
00
80
00
多个线程修改数据 内容就改乱了
#coding=utf-8
import time, threading
# 假定这是你的银行存款:
balance = 0
def change_it(n):
# 先存后取,结果应该为0:
global balance
balance = balance + n
balance = balance - n
print '-----------'
print 'thread %s is running...' % threading.current_thread().name
print balance
print '-----------'
def run_thread(n):
for i in range(100000):
change_it(n)
threads = []
t1 = threading.Thread(target=run_thread,name='xxyy11', args=(5,))
threads.append(t1)
t2 = threading.Thread(target=run_thread,name='xxyy22', args=(8,))
threads.append(t2)
for t in threads:
t.start()
t.join()
print 'thread %s ended.' % threading.current_thread().name
-----------
-----------
thread xxyy11 is running...thread xxyy22 is running...
0
-----------
-----------
thread xxyy22 is running...
0
-----------
8
----------------------
thread xxyy22 is running...
0
#coding=utf-8
import time, threading
# 假定这是你的银行存款:
balance = 0
lock = threading.Lock()
def change_it(n):
# 先存后取,结果应该为0:
global balance
balance = balance + n
balance = balance - n
#print n
print balance
def run_thread(n):
for i in range(100000):
# 先要获取锁:
lock.acquire()
try:
# 放心地改吧:
change_it(n)
finally:
# 改完了一定要释放锁:
lock.release()
threads = []
t1 = threading.Thread(target=run_thread,name='xxyy11', args=(6,))
threads.append(t1)
t2 = threading.Thread(target=run_thread,name='xxyy22', args=(7,))
threads.append(t2)
for t in threads:
t.start()
t.join()
print 'thread %s ended.' % threading.current_thread().name