标签:src 线程锁 code 其他 isp 分享 执行函数 imp star
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() mutex2 = Lock() 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()
当两个线程正在争抢对方已经加锁的,所以只能等待对方释放锁
死锁发生的条件 有多个线程 多个锁 如果只有一个锁 无论是LOCK RLOK 卡不死(前提是逻辑上没有错误)
RLock 就算你的代码逻辑不对 同一个线程多次对一个锁执行acquire 也不会卡死
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()
Semaphore 相当于限制执行代码的线程数量
默认为不限制
from threading import Thread,Semaphore,current_thread,active_count import time sm = Semaphore(3)# def task(): sm.acquire()#不限制线程的生成,但是限制当前执行函数的线程 for i in range(5): time.sleep(0.1) print(current_thread()) sm.release() def task1(): for i in range(5): time.sleep(0.1) print(current_thread()) for i in range(5): t = Thread(target=task) t1 = Thread(target=task1) t.start() t1.start() print(active_count())
标签:src 线程锁 code 其他 isp 分享 执行函数 imp star
原文地址:https://www.cnblogs.com/msj513/p/9937226.html