File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ # encoding: utf-8
2+ __author__ = 'zhanghe'
3+
4+ from multiprocessing import Process , Queue
5+ import time
6+ import random
7+
8+
9+ def write (q ):
10+ """
11+ 写数据进程执行的代码
12+ :param q:
13+ :return:
14+ """
15+ for value in ['A' , 'B' , 'C' ]:
16+ print 'Put %s to queue...' % value
17+ q .put (value )
18+ time .sleep (random .random ())
19+
20+
21+ def read (q ):
22+ """
23+ 读数据进程执行的代码
24+ :param q:
25+ :return:
26+ """
27+ while True :
28+ value = q .get (True )
29+ print 'Get %s from queue.' % value
30+
31+
32+ if __name__ == '__main__' :
33+ # 父进程创建Queue,并传给各个子进程,一个写,一个读,从而实现进程间通信:
34+ queue = Queue ()
35+ pw = Process (target = write , args = (queue ,))
36+ pr = Process (target = read , args = (queue ,))
37+ # 启动子进程pw,写入:
38+ pw .start ()
39+ # 启动子进程pr,读取:
40+ pr .start ()
41+ # 等待pw结束:
42+ pw .join ()
43+ # pr进程里是死循环,无法等待其结束,只能强行终止:
44+ pr .terminate ()
You can’t perform that action at this time.
0 commit comments