使用Pipe方法通信

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Pipe方法通信相关的知识,希望对你有一定的参考价值。

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

def proc_send(pipe,urls):
    for url in urls:
        print Process (%s) send: %s % (os.getpid(),url)
        pipe.send(url)
        time.sleep(random.random())

def proc_recv(pipe):
    while True:
        print Process (%s) rev: %s % (os.getpid(),pipe.recv())
        time.sleep(random.random())

if __name__ == __main__:
    pipe = Pipe()
    p1 = Process(target=proc_send, args=(pipe[0],[url_+str(i) for i in range(10)]))
    p2 = Process(target=proc_recv, args=(pipe[1],))
    p1.start()
    p2.start()
    p1.join()
    p2.join()

 Process方法: 

  “args:”用于传递参数,作用于"target="后跟的函数

  

Process (5396) send: url_0
Process (3860) rev: url_0
Process (5396) send: url_1
Process (3860) rev: url_1
Process (5396) send: url_2
Process (5396) send: url_3
Process (3860) rev: url_2
Process (5396) send: url_4
Process (5396) send: url_5
Process (3860) rev: url_3
Process (5396) send: url_6
Process (3860) rev: url_4
Process (5396) send: url_7
Process (3860) rev: url_5
Process (3860) rev: url_6
Process (5396) send: url_8
Process (3860) rev: url_7
Process (3860) rev: url_8
Process (5396) send: url_9
Process (3860) rev: url_9

 

The Pipe() function returns a pair of connection objects connected by a pipe which by default is duplex (two-way).

from multiprocessing import Process, Pipe

def f(conn):
    conn.send([42, None, hello])
    conn.close()

if __name__ == __main__:
    parent_conn, child_conn = Pipe()
    p = Process(target=f, args=(child_conn,))
    p.start()
    print parent_conn.recv()   # prints "[42, None, ‘hello‘]"
    p.join()

The two connection objects returned by Pipe() represent the two ends of the pipe. Each connection object has send() and recv()methods (among others). Note that data in a pipe may become corrupted if two processes (or threads) try to read from or write to the same end of the pipe at the same time. Of course there is no risk of corruption from processes using different ends of the pipe at the same time.

以上是关于使用Pipe方法通信的主要内容,如果未能解决你的问题,请参考以下文章

1 代码片段1

fork()、pipe() 和 exec() 进程创建和通信

Python子进程:使用Pipe和通信的困难

使用 stdout/stderr 以外的管道与子进程通信

第35篇 进程之间的通信 Queue Pipe 进程池Pool,p.apply()方法,p.apply_async()方法

Python 3 利用 subprocess 实现管道( pipe )交互操作读/写通信