锁——死锁——单个锁锁死
锁:
from threading import Thread,Lock # 创建一个互斥锁 mutex = Lock() def task1(): # 锁定 mutex.acquire() for i in range(100): print("===================") # 打开 mutex.release() def task2(): mutex.acquire() for i in range(100): print("!!!!!!!!!!!!!!!!!!") mutex.release() def task3(): mutex.acquire() for i in range(100): print("********************") mutex.release() t1 = Thread(target=task1) t2 = Thread(target=task2) t3 = Thread(target=task3) t1.start() t2.start() t3.start()
死锁:
from threading import Thread,Lock import time,random mutex1 = Lock() #创建一个锁1 mutex2 = Lock() #创建一个锁2 def fun1(): mutex1.acquire() print("抢到了锁1") time.sleep(1) mutex2.acquire() print("抢到了锁2") mutex2.release() print("释放了锁2") mutex1.release() print("释放了锁1") def fun2(): mutex2.acquire() print("抢到了锁2") time.sleep(1) mutex1.acquire() print("抢到了锁1") mutex1.release() print("释放了锁2") mutex2.release() print("释放了锁1") # def fun3(): # fun1() # fun2( t1 = Thread(target=fun1) t1.start() t2 = Thread(target=fun2) t2.start()
from threading import Thread,Lock,current_thread,RLock import time # 叉子 locka = RLock() # 盘子 lockb = RLock() def task1(): print(current_thread()) locka.acquire() print("抢到叉子 需要盘子") time.sleep(0.1) lockb.acquire() print("吃饭") lockb.release() locka.release() def task2(): print(current_thread()) lockb.acquire() print("抢到盘子 需要叉子") time.sleep(0.1) locka.acquire() print("吃饭") locka.release() lockb.release() t1 = Thread(target=task1) t1.start() t2 = Thread(target=task2) t2.start() # 死锁发生的条件 有多个线程 多个锁 如果只有一个锁 无论是LOCK RLOK 卡不死(前提是逻辑上没有错误) # RLock 就算你的代码逻辑不对 同一个线程多次对一个锁执行acquire 也不会卡死
单个锁:(递归锁/重入锁)
单个锁能不能锁死____答案是肯定的:
from threading import Thread,Lock,RLock,current_thread l = Lock() # 互斥锁 # l.acquire() # print("zxxzxxxzxzx") # l.acquire() # print("aaaaaaaaa") # RLock 递归锁 重入锁 可以多次执行acquire # lock = RLock() # # lock.acquire() # print("aaaaaaaaaaa") # lock.acquire() # print("bbbbbbbbbbb") import time lock = RLock() # 对于同一个线程而言 可以多次acquire 其他线程会被阻塞 def task(): lock.acquire() for i in range(5): time.sleep(1) print(current_thread()) lock.release() Thread(target=task).start() Thread(target=task).start()
信号量:(也是一种锁)
from threading import Thread,Semaphore,current_thread,active_count import time # 用于控制 同时执行被锁定代码的线程数量 也就是线程的并发数量 # 也是一种锁 sm = Semaphore(1) def task(): sm.acquire() for i in range(10): print(current_thread()) time.sleep(0.5) sm.release() def task2(): for i in range(10): print(current_thread()) time.sleep(0.5) for i in range(5): Thread(target=task).start() Thread(target=task2).start() print(active_count())