进程间通信

参考博客:http://blog.csdn.net/HeatDeath/article/details/72844120

一、前言

  线程存在于进程中,对于同一个进程内的线程,该进程内的资源是共享的,各个线程可以竞争获取。而不同的进程有独立的内存空间,它们之间不能直接相互访问,那么进程和进程间如何相互通信呢?

二、进程间通信

  2.1 Queue()

  在线程中有个队列queue,典型的应用在生产者和消费者模型中。而Queue()则用于进程间通信,使用和线程queue差不多。  

from multiprocessing import Process, Queue
import os
import time
import random


# 写数据进程执行的代码:
def write(x):
    print('Process to write: %s' % os.getpid())
    for value in ['A', 'B', 'C']:
        print('Put %s to queue...' % value)
        x.put(value)
        time.sleep(random.random())


# 读数据进程执行的代码:
def read(x):
    print('Process to read: %s' % os.getpid())
    while True:
        value = x.get()
        print('Get %s from queue.' % value)


if __name__ == '__main__':
    # 父进程创建Queue,并传给各个子进程:
    q = 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()

  2.2 Pipe()

  Pipe()函数返回一对由管道连接的连接对象,默认情况下是双工(双向)。

  Pipe()返回的两个连接对象代表管道的两端。 每个连接对象都有send()和recv()方法(等等) 

rom multiprocessing import Process, Pipe


def f(conn):
    conn.send([1, 2, 3])  # 子进程发送
    while True:
        print('receive from parent process:', conn.recv())   # 子进程接收

if __name__ == '__main__':
    parent_conn, child_conn = Pipe()   # 定义连接对象
    p = Process(target=f, args=(child_conn,))
    p.start()
    print('receive from child process:', parent_conn.recv())
    parent_conn.send('123')
    p.terminate()


# 输出
receive from child process: [1, 2, 3]
receive from parent process: 123

  

原文地址:https://www.cnblogs.com/bigberg/p/7997809.html