为什么如下代码的打印为
end
代码如下:
#-*- coding=utf-8 -*-
import os,time,random
from multiprocessing import Process,Pool,Queue
def pidprint(st):
print("pid(%s):"%os.getpid(),st)
def write(q):
pidprint("start write")
while True:
q.put(time.strftime("%H:%M:%s",time.localtime()))
time.sleep(1)
def read(q):
pidprint("start read")
while True:
pidprint(q.get(True))
if __name__ == '__main__':
q = Queue()
p = Pool(2)
p.apply_async(read,args=(q,))
p.apply_async(write,args=(q,))
time.sleep(1)
p.close()
p.join()
print('end')
队列Queue不能直接创建,而需要从Manager获得, 这样才能在子进程里共享
程序会输出
pid(32157): start read
pid(32158): start write
pid(32157): 21:55:1516974937
pid(32157): 21:55:1516974938
pid(32157): 21:55:1516974939
......