让线程相互通信的最佳方式



我目前有一个项目,我将有两个不同函数的多个线程运行。

def first_func():
while True:
#do_something...
#depending on "something" xy may be set to true
if xy == True:
#resume all threads for function second_func()
def second_func():
#do something
#do another thing
#wait until first_func tells us to resume...
#once first_func tells us to resume, we do more stuff..

从本质上讲,我将有数百个线程为second_func运行,它们将执行一些操作,然后什么也不做。一旦在运行first_func的线程中意味着某个条件,则所有为second_func运行的线程都将恢复其操作。我想知道最好的方法是什么?

我的两个想法是second_func()不断检查全局变量(在这种情况下为xy(是否为True,然后继续,但如果我每0.1秒左右有数百个线程检查一个变量的状态,这似乎会占用大量内存。第二个想法是让first_func建立一个本地websocket服务器,让second_func线程连接到它,然后等待,直到first_func在连接上说var是True,然后继续。

我觉得必须有一个比我上面的两个想法更好的方法。有什么想法吗?第一个函数应该能够";警报";在CCD_ 11变为CCD_。

标准pythonthreading.Event对象在这里运行良好:

go_flag = threading.Event()
def coordinator():
do_some_work()
go_flag.set()   # <- allow workers to proceed
def worker():
do_some_work()
do_more_work()

go_flag.wait()  # <- wait for coordinator to say "ok"

do_even_more_work()

最新更新