我想用并行执行来实现一个简单的python程序。它是I/O绑定的,所以我认为线程是合适的(与流程相反)。在阅读Queue和fork的文档后,我认为类似下面的内容可能会起作用。了解os.fork和Queue.Queue
q = Queue.Queue()
if os.fork(): # child
while True:
print q.get()
else: # parent
[q.put(x) for x in range(10)]
但是,get()调用永远不会返回。我认为一旦其他线程执行put()调用就会返回。使用线程模块,事情表现得更像我所料:
q = Queue.Queue()
def consume(q):
while True:
print q.get()
worker = threading.Thread (target=consume, args=(q,))
worker.start()
[q.put(x) for x in range(10)]
我只是不明白为什么fork方法不会做同样的事情。我错过了什么?
提及'multiprocessing'的+1。 – 2012-03-29 21:04:16