Python:IPC-Pipe与IPC-Manger

来源:转载

1,IPC-PIPE:

管道 pipe

from multiprocessing import Processfrom multiprocessing import Pipep1,p2 = Pipe() #支持双向通信# sendp1.send('菠萝蜜干')# recvprint(p2.recv())p2.send('酸奶')# p2.close()print(p1.recv())print(p1.recv()) #管道里没有值会报错: EOFError
2,用管道也能实现生产者消费者模型
 1 from multiprocessing import Process,Pipe,Lock 2 3 def consumer(p,name,lock): 4 produce, consume=p 5 produce.close() 6 while True: 7 lock.acquire() 8 baozi=consume.recv() 9 lock.release()10 if baozi:11 print('%s 收到菠萝蜜干:%s' %(name,baozi))12 else:13 consume.close()14 break15 16 def producer(p,n):17 produce, consume=p18 consume.close()19 for i in range(n):20 produce.send(i)21 produce.send(None)22 produce.send(None)23 produce.close()24 25 if __name__ == '__main__':26 produce,consume=Pipe()27 lock = Lock()28 c1=Process(target=consumer,args=((produce,consume),'c1',lock))29 c2=Process(target=consumer,args=((produce,consume),'c2',lock))30 p1=Process(target=producer,args=((produce,consume),10))31 c1.start()32 c2.start()33 p1.start()34 35 produce.close()36 consume.close()37 38 c1.join()39 c2.join()40 p1.join()41 print('主进程')

3,IPC-Manager

import timefrom multiprocessing import Managerfrom multiprocessing import Process# Manager是一个类 就提供了可以进行数据共享的一个机制 提供了很多数据类型 dict listdef func(dic): print(dic) while True: print(dic) time.sleep(3)if __name__ == '__main__': m = Manager() d = m.dict({'count':0}) print(d) p = Process(target=func,args=(d,)) p.start() d['count'] = 0from multiprocessing import Manager,Process,Lockdef work(d,lock): lock.acquire() d['count'] -= 1 lock.release()if __name__ == '__main__': lock= Lock() m = Manager() dic=m.dict({'count':100}) # 共享的数据 l = [] for i in range(100): p=Process(target=work,args=(dic,lock)) p.start() l.append(p) [p.join() for p in l] print(dic)

分享给朋友:
您可能感兴趣的文章:
随机阅读: