python - 在python中通知并释放锁后,其他线程也不会唤醒
问题描述
import time
from threading import *
import random
class appointment:
def patient(self):
for _ in range(2):
condition_object.acquire()
print('patient john waiting for appointment')
condition_object.notify()
condition_object.wait() # Thread is in waiting state
print('patiend john successfully got the appointment')
condition_object.notify()
condition_object.release()
print('patient john is done')
def doctor(self):
for _ in range(2):
print('doctor in chamber')
condition_object.acquire()
print('doctor jarry checking the time for appointment')
time=0
time=random.randint(1,13)
print('oppointed time is {} PM'.format(time))
condition_object.notify()
print('doctor is going to wait')
condition_object.wait(1.1)
print('doctor is about to leave')
condition_object.release()
print('doctor is done')
condition_object = Condition()
class_obj=appointment()
T1 = Thread(target=class_obj.patient)
T2 = Thread(target=class_obj.doctor)
T1.start()
T2.start()
T1.join()
T2.join()
print("\nEND\n")
这是一个典型的消费者生产者线程代码。并且在 2 个循环结束时,我希望当患者线程通知其他线程并释放锁时,等待的医生线程会唤醒。但是等待的医生线程没有醒来(即使我设置了一个计时器)。
如果我在 patient() 函数的末尾使用 wait() 而不是 release,则医生线程会唤醒,但是在我从医生线程释放锁后,患者函数并没有唤醒。我真的很困惑。
为什么从另一个线程释放锁后医生线程没有唤醒?
和
为什么医生线程只有在从另一个线程调用 wait() 后才被唤醒?
解决方案
我通过以下方式更改了您的代码,它似乎可以正常工作:
from threading import *
import random
class Appointment:
def __init__(self, cond: Condition):
self.cond = cond
def patient(self):
with self.cond:
for _ in range(2):
print('Patient John waiting for appointment')
self.cond.notify()
self.cond.wait() # Thread is in waiting state
print('Patient John successfully got the appointment')
self.cond.notify()
print('Patient John is done')
def doctor(self):
print('Doctor in chamber')
with self.cond:
for _ in range(2):
print('Doctor Jarry checking the time for appointment')
t = random.randint(1, 13)
print('appointed time is {} PM'.format(t))
self.cond.notify()
print('Doctor is going to wait')
self.cond.wait()
print('Doctor is about to leave')
print('Doctor is done')
if __name__ == '__main__':
_condition_object = Condition()
class_obj = Appointment(_condition_object)
ths = [Thread(target=class_obj.patient), Thread(target=class_obj.doctor)]
[th.start() for th in ths]
[th.join() for th in ths]
print("\nEND\n")
推荐阅读
- wordpress - 使用重力形式自动搜索和填充字段
- vba - 使用 VBA 从网站中提取电子邮件地址
- docker - 从 docker-compose 替换 NGINX 配置中的环境变量
- python - fastai.vision 导入错误:如何修复导入错误以便我可以使用 ImageDataBunch.from_folder?
- linux - Upboard 无法访问引脚
- xamarin.forms - Xamarin.Forms 将视频设置为启动画面
- postgresql - 仅当两列冲突时才插入?
- sql - 为计算列添加强制 DECIMAL 类型的列
- postgresql - 即使删除了某些行,带有种子值的随机排序是否会再次返回相同的集合?
- unity3d - 我还能使用过时的资产吗?