python管道怎么使用_如何在多个流程中正确使用管道(>2)

不要对多个用户使用管道。documentation显式地表示,当两个以上的进程读取或写入时,它将被损坏。你有;两个读者。在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.

所以使用Queue,或者JoinableQueue。在from multiprocessing import Process, JoinableQueue

from Queue import Empty

import time

def consumer(que, pid):

while True:

try:

item = que.get(timeout=10)

print("%s consume:%s" % (pid, item))

que.task_done()

except Empty:

break

print('Consumer done')

def producer(sequence, que):

for item in sequence:

print('produce:', item)

que.put(item)

time.sleep(1)

if __name__ == '__main__':

que = JoinableQueue()

# create two consumer process

cons_p1 = Process(target=consumer, args=(que, 1))

cons_p1.start()

cons_p2 = Process(target=consumer, args=(que, 2))

cons_p2.start()

sequence = [i for i in range(10)]

producer(sequence, que)

que.join()

cons_p1.join()

cons_p2.join()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值