【发布时间】:2016-07-23 19:48:10
【问题描述】:
我正在学习 python 多线程和队列。下面创建了一堆线程,它们通过队列将数据传递到另一个线程进行打印:
import time
import threading
import Queue
queue = Queue.Queue()
def add(data):
return ["%sX" % x for x in data]
class PrintThread(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
data = self.queue.get()
print data
self.queue.task_done()
class MyThread(threading.Thread):
def __init__(self, queue, data):
threading.Thread.__init__(self)
self.queue = queue
self.data = data
def run(self):
self.queue.put(add(self.data))
if __name__ == "__main__":
a = MyThread(queue, ["a","b","c"])
a.start()
b = MyThread(queue, ["d","e","f"])
b.start()
c = MyThread(queue, ["g","h","i"])
c.start()
printme = PrintThread(queue)
printme.start()
queue.join()
但是,我只看到打印出来的第一个线程的数据:
['aX', 'bX', 'cX']
然后没有别的,但程序没有退出。我必须终止进程才能让它退出。
理想情况下,在每个MyThread 进行数据处理并将结果放入队列之后,该线程应该退出吗?同时PrintThread 应该获取队列中的任何内容并打印出来。
在所有MyThread 线程完成并且PrintThread 线程完成处理队列中的所有内容之后,程序应该干净地退出。
我做错了什么?
编辑:
如果每个MyThread 线程都需要一段时间来处理,有没有办法保证PrintThread 线程会等待所有MyThread 线程完成后再退出?
这样打印线程肯定会处理队列中所有可能的数据,因为所有其他线程都已经退出。
例如,
class MyThread(threading.Thread):
def __init__(self, queue, data):
threading.Thread.__init__(self)
self.queue = queue
self.data = data
def run(self):
time.sleep(10)
self.queue.put(add(self.data))
上述修改将等待 10 秒,然后再将任何内容放入队列。打印线程会运行,但我认为它退出太早了,因为队列上还没有数据,所以程序什么也没打印出来。
【问题讨论】:
标签: python multithreading python-2.7 python-multithreading