python 进程间共享数据 (三)

来源:互联网 发布:java图片压缩开源框架 编辑:程序博客网 时间:2024/05/29 03:10

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, 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__':
    # 父进程创建Queue,并传给各个子进程:
    = Queue()
    pw = Process(target=write, args=(q,))
    pr = Process(target=read, args=(q,))
    # 启动子进程pw,写入:
    pw.start()
    # 启动子进程pr,读取:
    pr.start()
    # 等待pw结束:
    pw.join()
    # pr进程里是死循环,无法等待其结束,只能强行终止:
    pr.terminate()

  from : 网上整理

0 0
原创粉丝点击