您可以使用
Queue.Queue(或
queue.Queue在Python 3中):
import threadingimport time from Queue import Queueprint_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实例传递给每个线程,然后将消息发送给
Threadusing
queue.put。我们等待消息到达
run方法中,该方法
Thread实际上是在单独的执行线程中运行的对象的一部分。收到消息后,我们将调用
do_thing_with_message,它将在同一后台线程中运行。
我还向
threading.Lock代码中添加了,以使打印到标准输出的图像不会混淆。
编辑:
如果您希望能够向线程传递多条消息,只需使用循环:
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)



