Python:IPC-Pipe与IPC-Manger

1,IPC-PIPE:

管道 pipe

from multiprocessing import Process
from multiprocessing import Pipe
p1,p2 = Pipe()  #支持双向通信
# send
p1.send('菠萝蜜干')
# recv
print(p2.recv())
p2.send('酸奶')
# p2.close()
print(p1.recv())
print(p1.recv())  #管道里没有值会报错: EOFError
2,用管道也能实现生产者消费者模型
from multiprocessing import Process,Pipe,Lock
 
 def consumer(p,name,lock):
     produce, consume=p
     produce.close()
     while True:
         lock.acquire()
         baozi=consume.recv()
         lock.release()
         if baozi:
             print('%s 收到菠萝蜜干:%s' %(name,baozi))
         else:
             consume.close()
             break
 
 def producer(p,n):
     produce, consume=p
     consume.close()
     for i in range(n):
         produce.send(i)
     produce.send(None)
     produce.send(None)
     produce.close()
 
 if __name__ == '__main__':
     produce,consume=Pipe()
     lock = Lock()
     c1=Process(target=consumer,args=((produce,consume),'c1',lock))
     c2=Process(target=consumer,args=((produce,consume),'c2',lock))
     p1=Process(target=producer,args=((produce,consume),10))
     c1.start()
     c2.start()
     p1.start()
 
     produce.close()
     consume.close()
 
     c1.join()
     c2.join()
     p1.join()
     print('主进程')

3,IPC-Manager

import time
from multiprocessing import Manager
from multiprocessing import Process
# Manager是一个类 就提供了可以进行数据共享的一个机制 提供了很多数据类型 dict list
def 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'] =from multiprocessing import Manager,Process,Lock
def 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)

相关推荐