1. 程式人生 > >(三)使用Pipe方法通信

(三)使用Pipe方法通信

size and become others logs dup res 參數 corrupt

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方法通信