标签:class print 线程 信号 rlock import pre random current
#死锁:锁只能抢一次,释放后被其他人抢 from threading import Thread,Lock,current_thread import time class MyThread(Thread): def run(self): self.f1() self.f2() def f1(self): mutexA.acquire() print("%s 抢到A锁" %current_thread().getName()) mutexB.acquire() print("%s 抢到B锁" %current_thread().getName()) print("%s 释放B锁" %current_thread().getName()) mutexB.release() print("%s 释放A锁" %current_thread().getName()) mutexA.release() def f2(self): mutexB.acquire() print("%s 抢到B锁" %current_thread().getName()) time.sleep(1) mutexA.acquire() print("%s 抢到A锁" %current_thread().getName()) print("%s 释放A锁" %current_thread().getName()) mutexA.release() print("%s 释放B锁" %current_thread().getName()) mutexB.release() if __name__=="__main__": mutexA=Lock() mutexB=Lock() for i in range(20): t=MyThread() t.start() # ‘‘‘ # Thread-758 抢到A锁 # Thread-758 抢到B锁 # Thread-758 释放B锁 # Thread-758 释放A锁 # Thread-758 抢到B锁 # Thread-759 抢到A锁 # ‘‘‘
# 递归锁:锁可以抢多次,acquire一次,count加1,release一次,count减1,直到count=0,锁最终释放别其他人抢
from threading import Thread,RLock,current_thread import time class MyThread(Thread): def run(self): self.f1() self.f2() def f1(self): mutex.acquire() print("%s 抢到锁" %current_thread().getName()) mutex.acquire() print("%s 抢到锁" %current_thread().getName()) print("%s 释放锁" %current_thread().getName()) mutex.release() print("%s 释放锁" %current_thread().getName()) mutex.release() def f2(self): mutex.acquire() print("%s 抢到锁" %current_thread().getName()) time.sleep(1) mutex.acquire() print("%s 抢到锁" %current_thread().getName()) print("%s 释放锁" %current_thread().getName()) mutex.release() print("%s 释放锁" %current_thread().getName()) mutex.release() if __name__=="__main__": mutex=RLock() for i in range(20): t=MyThread() t.start() ‘‘‘ Thread-808 抢到锁 Thread-808 抢到锁 Thread-808 释放锁 Thread-808 释放锁 Thread-810 抢到锁 Thread-810 抢到锁 Thread-810 释放锁 Thread-810 释放锁 ‘‘‘
#线程:信号量【锁】 from threading import Thread,current_thread,Semaphore import time,random sm=Semaphore(3) def work(): sm.acquire() print("target %s is running" %current_thread().getName()) time.sleep(random.randint(1,3)) sm.release() if __name__=="__main__": for i in range(10): t=Thread(target=work) t.start()
标签:class print 线程 信号 rlock import pre random current
原文地址:https://www.cnblogs.com/hapyygril/p/12590085.html