首页 > 解决方案 > wait_for 和条件 Python

问题描述

我以某种方式编写了这段代码,一次只允许一个作家,而作家工作时不能有读者。它有效,但我不知道为什么,我知道wait_for()要醒来有必要打电话notify(),但我没有而且仍然有效。

谢谢!

import threading
import time

condition = threading.Condition()

def test():
    return True

def reader(data):
    with condition:
        condition.wait_for(test)
    print('read')

def writer(data):
    with condition:
        time.sleep(5)
    print('write')

def runThread(data):
    if data["w"]: #writer
        writer(data)
    elif data["r"]: #reader
        reader(data)

def run():
    #something happens
    threading.Thread(target=runThread, daemon=True, ).start()

标签: pythonpython-3.xmultithreading

解决方案


推荐阅读