【问题标题】:Best way to have threads communicate with each other让线程相互通信的最佳方式
【发布时间】:2021-04-08 03:50:12
【问题描述】:

我目前有一个项目,我将运行具有 2 个不同功能的多个线程。

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 运行的线程将恢复它们的操作。我想知道最好的方法是什么?

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

我觉得必须有比我上面的两个想法更好的方法。有任何想法吗?第一个 func 应该能够在 xy 变为 True 的几毫秒内“提醒”所有第二个 func 线程。

【问题讨论】:

  • 每秒检查 10 次变量不需要任何内存。它确实使用CPU,但数量很少。但是,threading.Event 对象似乎正是您要查找的对象。
  • second_func 循环吗?也就是说,xy 会是假的,然后是真的,然后是假的,然后是真的,等等?
  • FWIW(题外话):不需要写if xy == True: 因为if xy: 就足够了。
  • 使用不断检查某事状态的忙等待循环不是一个好主意。相反,使用threading.event() 之类的东西,您可以在一个线程中使用它的wait() 方法来阻塞,直到其他线程设置其内部标志(或等待超时)。

标签: python multithreading


【解决方案1】:

标准的 python threading.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()

【讨论】:

    猜你喜欢
    • 2015-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 2011-10-12
    • 1970-01-01
    相关资源
    最近更新 更多