Python 多线程,用于消息传递和避免处理器占用的队列

Python multithreading, Queues for messaging and avoiding processor hogging

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

# 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 之外还有更好的范例吗?我试过休眠,但线程需要立即响应。

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

所以只需删除 self.inbox.empty():

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