线程锁,递归锁
# from threading import Thread,Lock,current_thread # import os ,time # def task(): # global n # print('%s is running'%current_thread().getName()) # temp=n # time.sleep(0.5) # n=temp-1 # if __name__=='__main__': # n=100 # lock=Lock() # threads_list=[] # start_time=time.time() # for i in range(100): # t=Thread(target=task) # threads_list.append(t) # t.start() # for t in threads_list: # t.join() # stop_time=time.time() # print("zhu%s:%s"%(stop_time-start_time,n)) # Thread-99 is running # Thread-100 is running # zhu0.5460002422332764:99
无锁,执行时间最短,但不能保证数据正确性(在同一时间所有进程都拿到了初始值100,然后开始计算)
# from threading import Thread,Lock,current_thread # import os ,time # def task(lock): # global n # print('%s is running'%current_thread().getName()) #lock 之前的代码可以先执行,然后等待别的线程释放锁 # lock.acquire() # temp=n # time.sleep(0.5) # n=temp-1 # lock.release() # if __name__=='__main__': # n=100 # lock=Lock() # thread_list=[] # start_time=time.time() # for i in range(100): # t=Thread(target=task,args=(lock,)) # thread_list.append(t) # t.start() # for t in thread_list: # t.join() # stop_time=time.time() # print('zhu %s:%s'%(stop_time-start_time,n)) # Thread-96 is running # Thread-97 is running # Thread-98 is running # Thread-99 is running # Thread-100 is running # zhu 50.00099992752075:0 加锁,效率变低,但数据呜呜 from threading import Thread,Lock,current_thread import os ,time def task(): global n print('%s is running'%current_thread().getName()) #如果lock之前的代码很长,将会很费时间,每次都是一个一个从头执行,不能先执行 # lock.acquire() temp=n time.sleep(0.5) n=temp-1 # lock.release() if __name__=='__main__': n=100 start_time=time.time() for i in range(100): t=Thread(target=task) t.start() t.join() stop_time=time.time() print('zhu %s:%s'%(stop_time-start_time,n)) # Thread-95 is running # Thread-96 is running # Thread-97 is running # Thread-98 is running # Thread-99 is running # Thread-100 is running # zhu 50.01300024986267:0
p.start()后立即p.join(),等于串行,等于把所有的代码都执行一遍
from threading import Thread,Lock,RLock import time A=B=RLock()
#A=Lock()
#B=Lock() class MyThread(Thread): def run(self): self.func1() self.func2() def func1(self): A.acquire() print("拿到A") B.acquire() print("拿到B") B.release() A.release() def func2(self): B.acquire() print("2拿到B") time.sleep(2) A.acquire() print("2拿到A") A.release() B.release() if __name__=='__main__': for i in range(10): t=MyThread() t.start() # 拿到A # 拿到B # 2拿到B,#等待A # 拿到A #等待 #Rlock # 拿到A # 拿到B # 2拿到B # 2拿到A # 拿到A # 拿到B # 2拿到B # 2拿到A
一个线程拿到锁,counter加1,该线程内又碰到加锁的情况,则counter继续加1,这期间所有其他线程都只能等待,等待该线程释放所有锁,即counter递减到0为止