Python的multiprocessing模块包装了底层的机制,提供了Queue、Pipes等多种方式来交换数据。
我们以Queue为例,在父进程中创建两个子进程,一个往Queue里写数据,一个从Queue里读数据:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
from multiprocessing import Process, import os, # def write(q): for value in [ 'A' , 'B' , 'C' ]: print 'Put % value q.put(value) time.sleep(random.random()) # def read(q): while True : value = q.get( True ) print 'Get % value if __name__ = = '__main__' : # q = Queue() pw = Process(target = write, = (q,)) pr = Process(target = read, = (q,)) # pw.start() # pr.start() # pw.join() # pr.terminate() |
from : 网上整理