【问题标题】:Python multithreading, Queues for messaging and avoiding processor hoggingPython 多线程、消息队列和避免处理器占用
【发布时间】:2015-04-08 18:15:38
【问题描述】:

我有一个进程使用队列在线程之间发送消息。

# receiver.py
class Receiver(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.daemon = True
        self.inbox = Queue.Queue()

    def run(self):
        while True:
            if not self.inbox.empty():
                msg = self.inbox.get()
                # do other stuff


# main.py
def main():
    R1 = Receiver()
    R2 = Receiver()
    R1.start()
    R2.start()

    # spin up child threads that can also stuff messages into Receiver() inboxes

    while True:
        msg = "You're hogging processor time"
        R1.inbox.put(msg)
        R2.inbox.put(msg)
        # do a whole bunch more fancy stuff

if __name__ == '__main__':
    main()

当我查看分配给此进程的处理器时间百分比时,它通常固定在 > 90%。

除了 while-True-check-inbox 之外,还有更好的范例吗?我试过休眠,但线程需要立即响应。

【问题讨论】:

  • 你可以在你的“while”周期内睡觉,这不应该影响线程。

标签: python multithreading processor


【解决方案1】:

Queue.get 将等待(阻塞)直到队列中有东西。在此等待期间,线程将休眠,允许其他线程(和进程)运行。

所以只需删除您对self.inbox.empty() 的检查:

def run(self):
    while True:
        msg = self.inbox.get()
        # do other stuff

【讨论】:

  • 这是个好消息,我没有意识到这一点。谢谢!我会在下一个版本中尝试一下,并尽快报告。 :)
  • 再次阅读文档,我注意到 get() 方法也接受超时。这可能也会派上用场,因为我们正在处理异步问题。
  • 是的。在使用超时设置 get() 方法后,我们的 CPU 使用率从 > 90% 下降到平均 12 - 15% 左右。感谢您的真棒建议。现在看起来很明显,但在有人指出之前它永远不会明显:)
猜你喜欢
  • 1970-01-01
  • 2018-12-05
  • 1970-01-01
  • 2011-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-13
  • 2017-06-10
相关资源
最近更新 更多