码迷,mamicode.com
首页 > 其他好文 > 详细

(三)使用Pipe方法通信

时间:2017-10-23 01:05:03      阅读:288      评论:0      收藏:0      [点我收藏+]

标签:rom   return   python   font   course   sleep   blog   iter   nts   

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

标签:rom   return   python   font   course   sleep   blog   iter   nts   

原文地址:http://www.cnblogs.com/yitiaoluyu/p/7712723.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!