使用Queue for循环(Python)

时间:2017-07-13 23:03:55

标签: python queue multiprocessing

我无法理解以下代码的工作原理:

from multiprocessing import Process, Queue
import os, time, random


def write(q):
    for value in ['A', 'B', 'C']:
        print 'Put %s to queue...' % value
        q.put(value)
        time.sleep(random.random())

def read(q):
    while True:
        value = q.get(True)
        print 'Get %s from queue.' % value

if __name__=='__main__': 
    q = Queue()
    pw = Process(target=write, args=(q,))
    pr = Process(target=read, args=(q,))

    pw.start()
    pr.start()
    pw.join()

    pr.terminate()

似乎pw.join()同步pwpr,但我不知道它是如何工作的。我认为pr.start()pw.start()完成后继续进行,这意味着只有在Get %s from queue打印完Put %s to queue...后才能收到pool()。我还认为process用于多进程,BoundingLayer仅用于单个进程,但现在看来我完全错了。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

首先,你的问题应该被标题为"如何在python中加入工作"

join()阻塞调用线程(在本例中是主线程),直到调用其连接的进程终止。请参阅定义here

所以在你的代码中你阻止了pr.terminate()的调用,直到pw结束。当你删除pw.join语句时,进程pr在启动后很快终止,这就是为什么你没有看到任何" Get ..."消息。