我有一个类在我的应用程序中的单独线程中运行。我可以同时运行多个线程,并且这些线程是守护进程。经过一段时间后,some这些线程需要接收并处理消息。我该怎么做呢?
我的代码示例如下所示:
import threading
import time
class MyThread(threading.Thread):
def __init__(self, args=(), kwargs=None):
threading.Thread.__init__(self, args=(), kwargs=None)
self.daemon = True
self.receive_messages = args[0]
def run(self):
print threading.currentThread().getName(), self.receive_messages
def do_thing_with_message(self, message):
if self.receive_messages:
print threading.currentThread().getName(), "Received %s".format(message)
if __name__ == '__main__':
threads = []
for t in range(10):
threads.append( MyThread(args=(t % 2 == 0,)))
threads[t].start()
time.sleep(0.1)
for t in threads:
t.do_thing_with_message("Print this!")
这输出:
Thread-1 True
Thread-2 False
Thread-3 True
Thread-4 False
Thread-5 True
Thread-6 False
Thread-7 True
Thread-8 False
Thread-9 True
Thread-10 False
MainThread Received %s
MainThread Received %s
MainThread Received %s
MainThread Received %s
MainThread Received %s
然而,我预计最后五行与MainThread
,而不是%s
,我希望它对我来说Print this!
,像这样:
Thread-1 True
Thread-2 False
Thread-3 True
Thread-4 False
Thread-5 True
Thread-6 False
Thread-7 True
Thread-8 False
Thread-9 True
Thread-10 False
Thread-1 Received Print this!
Thread-3 Received Print this!
Thread-5 Received Print this!
Thread-7 Received Print this!
Thread-9 Received Print this!
如何正确地将这样的消息发送到正在运行的线程?
附录:
如果我在之后有这个块Print this!
阻止,并利用@dano的代码解决上述问题,它似乎没有响应这些新消息。
for t in threads:
t.queue.put("Print this again!")
time.sleep(0.1)
在这种情况下,我希望输出的结尾看起来像这样
Thread-1 Received Print this!
Thread-3 Received Print this!
Thread-5 Received Print this!
Thread-7 Received Print this!
Thread-9 Received Print this!
Thread-1 Received Print this again!
Thread-3 Received Print this again!
Thread-5 Received Print this again!
Thread-7 Received Print this again!
Thread-9 Received Print this again!