进程间的通信--Process


在父进程中创建两个子进程,一个往Queue里写数据,一个从Queue里读数据:

 1 from multiprocessing import Process,Queue
 2 import time
 3 import os
 4 
 5 
 6 def write(q):
 7     for i in "hello":
 8         print("----put item  %s"%i)
 9         q.put(i)
10         time.sleep(1)
11 
12 
13 def read(q):
14 
15     while 1:
16         if not q.empty():
17             print("----output----%s"%q.get())
18             time.sleep(1)
19 
20 
21 # 父进程创建Queue,并传给各个子进程:
22 q = Queue()
23 p_write = Process(target=write, args=(q,))
24 p_read = Process(target=read, args=(q,))
25 
26 # 写数据  也可以同时启动读数据和写数据进程
27 p_write.start()
28 p_write.join()
29 
30 # 读数据
31 p_read.start()
32 p_read.join()

执行结果