标签:int release rlock sleep 运行 def 并且 注意 另一个
from threading import Lock
lock_1 = Lock()
lock_1.acquire()
lock_1.acquire()
print(123)
# 打印结果:无法打印,并且程序阻塞住了
from threading import RLock
lock_2 = RLock()
lock_2.acquire()
lock_2.acquire()
print(123)
# 打印结果:123
from threading import Thread,RLock,Lock
import time
lock1 = Lock()
def foo(name):
lock1.acquire()
print(f"{name}抱起猫")
time.sleep(3) # 模拟线程被中断去执行其他的线程
lock1.acquire()
print(f"{name}抱起狗")
lock1.release()
lock1.release()
def foo1(name):
lock1.acquire() # 注意看锁的名字,和上面的不一样
print(f"{name}抱起狗")
lock1.acquire()
print(f"{name}抱起猫")
lock1.release()
lock1.release()
t = Thread(target=foo,args=('Cheer',)).start()
t1 = Thread(target=foo1,args=('PI',)).start()
# 打印结果:出现阻塞状态,程序一直不会结束,就一直僵着,因为两个线程都没有释放对方需要的锁
from threading import Thread,RLock,Lock
import time
lock1 = RLock()
def foo(name):
lock1.acquire()
print(f"{name}抱起猫")
time.sleep(3) # 模拟线程被中断去执行其他的线程
lock1.acquire()
print(f"{name}抱起狗")
lock1.release()
lock1.release()
def foo1(name):
lock1.acquire() # 注意看锁的名字,和上面的不一样
print(f"{name}抱起狗")
lock1.acquire()
print(f"{name}抱起猫")
lock1.release()
lock1.release()
t = Thread(target=foo,args=('Cheer',)).start()
t1 = Thread(target=foo1,args=('PI',)).start()
from threading import Thread,Semaphore
import time
# 信息量:也就是厕所开放多少个坑,一次性运行的线程数,之前的加锁了,一次只有一个线程通过,这次不一样了,这次好几个
# 实例化一个信息量
sem = Semaphore(4) # 括号里面的数值是开放多少个"坑位"
def foo(i):
sem.acquire() # 和锁的用法一样
print(f"哈哈哈,{i}进来了")
time.sleep(i+1)
sem.release()
print(f"哈哈哈,{i}干完了")
for i in range(10):
t = Thread(target=foo,args=(i,)).start()
标签:int release rlock sleep 运行 def 并且 注意 另一个
原文地址:https://www.cnblogs.com/xiongchao0823/p/11543737.html