##多线程资源共享使用问题
import threading import time def addNum(): global num #num -= 1 tmp = num time.sleep(0.00001) num = tmp-1 num = 100 thread_list = [] for i in range(100): t = threading.Thread(target=addNum) t.start() thread_list.append(t) for t in thread_list: t.join() print(num)
上面程序运行,num不会减到0。cpu执行了一个线程的tmp = num后,就切换到其他线程,有很多执行了tmp = num,所以所有线程的tmp大都是等于100的,执行num = tmp - 1的时候,num就可能等于99或者98之类的。
解决办法,加锁
步骤:1、新建锁
2、调用acquire()方法锁上,中间是执行代码
3、调用release()方法释放锁
1 import threading 2 import time 3 4 def addNum(): 5 global num 6 # num -= 1 7 r.acquire() # 锁上 8 tmp = num 9 time.sleep(0.00001) 10 num = tmp-1 11 r.release() # 释放锁 12 13 r = threading.Lock() # 拿到锁对象 14 num = 100 15 thread_list = [] 16 for i in range(100): 17 t = threading.Thread(target=addNum) 18 t.start() 19 thread_list.append(t) 20 21 for t in thread_list: 22 t.join() 23 24 print(num)
两个锁以上可能导致死锁,这里就不写例子了。
重用锁:threading.Rlock(),在对象里面的方法需要,比如下面这个取钱的例子
#01同步例子
1 import threading 2 import time 3 class Tickets: 4 def __init__(self): 5 self.ticket = 100 6 7 def sell_ticket(self): 8 while self.ticket > 0: 9 loc.acquire() 10 print('卖出',self.ticket,'票',threading.current_thread()) 11 self.ticket -= 1 12 loc.release() 13 time.sleep(0.0001) 14 15 if __name__ == '__main__': 16 ticket = Tickets() 17 t1 = threading.Thread(target=ticket.sell_ticket) 18 t2 = threading.Thread(target=ticket.sell_ticket) 19 t3 = threading.Thread(target=ticket.sell_ticket) 20 loc = threading.Lock() 21 t1.start() 22 t2.start() 23 t3.start()