首页 > 解决方案 > 在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() 后才被唤醒?

标签: pythonmultithreadingpython-multithreadingpython-3.9

解决方案


我通过以下方式更改了您的代码,它似乎可以正常工作:

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")

推荐阅读