在我的应用程序中,有一个类在单独的线程中运行。我可以一次运行多个线程,线程是守护进程。经过一段时间后,这些线程中的一些需要接收和处理消息。我该怎么做?
我的代码示例如下:
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!发布于 2014-09-18 05:21:02
为此,可以使用Queue.Queue (或Python3中的queue.Queue ):
import threading
import time
from Queue import Queue
print_lock = threading.Lock()
class MyThread(threading.Thread):
def __init__(self, queue, args=(), kwargs=None):
threading.Thread.__init__(self, args=(), kwargs=None)
self.queue = queue
self.daemon = True
self.receive_messages = args[0]
def run(self):
print threading.currentThread().getName(), self.receive_messages
val = self.queue.get()
self.do_thing_with_message(val)
def do_thing_with_message(self, message):
if self.receive_messages:
with print_lock:
print threading.currentThread().getName(), "Received {}".format(message)
if __name__ == '__main__':
threads = []
for t in range(10):
q = Queue()
threads.append(MyThread(q, args=(t % 2 == 0,)))
threads[t].start()
time.sleep(0.1)
for t in threads:
t.queue.put("Print this!")
for t in threads:
t.join()我们向每个线程传递一个Queue实例,并使用queue.put将消息发送到Thread。我们等待消息到达run方法,它是Thread对象的一部分,实际上运行在单独的执行线程中。一旦我们得到消息,我们就调用do_thing_with_message,它将在同一个后台线程中运行。
我还在代码中添加了一个threading.Lock,这样到stdout的打印就不会混淆。
编辑:
如果希望能够向线程传递多条消息,只需使用一个循环:
def run(self):
print threading.currentThread().getName(), self.receive_messages
while True:
val = self.queue.get()
if val is None: # If you send `None`, the thread will exit.
return
self.do_thing_with_message(val)https://stackoverflow.com/questions/25904537
复制相似问题