同步锁
线程申请到gillock才能被cpu执行
lock=threading.LOCK()
lock.acquire() 获取
lock.release() 释放
import threading,time def sub(): print(30) global num lock.acquire() num-=1 print(999) time.sleep(1) lock.release() print(25,t) num=100 l=[] lock=threading.Lock() for i in range(100): t=threading.Thread(target=sub) t.start() l.append(t) for t in l: t.join() print(num)
递归锁
用来解决死锁
r_lock=threading.RLock()
r_lock.acquire() 计算器加1,只要内部计算器>0,其它线程无法获取
r_lock.release() 计算器减1
递归锁:内部维持多把锁
import threading,time class Mythread(threading.Thread): def actionA(self): r_lock.acquire() print(self.name,'get A',time.ctime()) time.sleep(1) r_lock.acquire() print(self.name,'get B',time.ctime()) time.sleep(2) r_lock.release() r_lock.release() def actionB(self): r_lock.acquire() print(self.name, 'get B', time.ctime()) time.sleep(1) r_lock.acquire() print(self.name, 'get A', time.ctime()) time.sleep(2) r_lock.release() r_lock.release() def run(self): self.actionA() self.actionB() l=[] r_lock=threading.RLock() for i in range(5): t=Mythread() t.start() l.append(t) for t in l: print(4) t.join() print(3,t) print('结束')