Python多进程通信

Python多进程通信

Python的多进程通信提供了两种方法:Queue、Pipes。两者都在mutilprocessing模块中提供。

接下来以Queue队列为例,实现进程间的通信。在父进程创建两个子进程,分别承担生产、消费角色对同一个Queue进行操作。

#!/usr/bin/env python3
# -*- coding:utf-8 -*-  
'进程间通信'
'Process之间肯定是需要通信的,' \
'操作系统提供了很多机制来实现进程间的通信。' \
'Python的multiprocessing模块包装了底层的机制,' \
'提供了Queue、Pipes等多种方式来交换数据。'
__author__ = 'click'
__date__ = '2018/7/23 下午5:29'

from multiprocessing import Process, Queue

import time, random, os


# 网队列中写操作
def write(queue):
    print('队列的写入操作')

    for x in ['A', 'B', 'c']:
        print('插入的内容是%s' % (x))
        queue.put(x)
        time.sleep(random.random())


# 读操作

def read(queue):
    print('队列的读操作')
    # 这里要循环从队列中读取
    while True:
        s = queue.get(True)
        print('队列中读取的内容是%s' % (s))


if __name__ == '__main__':
    # 创建一个queue
    q = Queue()
    # 创建一个写操作的进程
    pw = Process(target=write, args=(q,))
    # 创建一个读操作的进程
    pr = Process(target=read, args=(q,))
    # 启动进程
    pw.start()
    pr.start()
    pw.join()
    pr.terminate()

执行结果:

队列的写入操作
插入的内容是A
队列的读操作
队列中读取的内容是A
插入的内容是B
队列中读取的内容是B
插入的内容是c
队列中读取的内容是c

Queue作为参数在write、read方法中传递,write往队列中添加数据。read从队列中获取新数据。并进行消费

例子源码

猜你喜欢

转载自blog.csdn.net/u012782882/article/details/81206535