Python: IPC-Pipe and IPC-Manger, ipc-pipeipc-manger
1, IPC-PIPE:
Pipeline pipe
From multiprocessing import Processfrom multiprocessing import Pipep1, p2 = Pipe () # support for bidirectional communication # sendp1.send ('jackfruit dry ') # recvprint (p2.recv () p2.send ('yogurt ') # p2.close () print (p1.recv () print (p1.recv () # if there is no value in the pipeline, an error is returned: EOFError
2. producer and consumer models can also be implemented using Pipelines
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 received jackfruit dried: % 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 ('main Process ')
3. IPC-Manager
Import timefrom multiprocessing import Managerfrom multiprocessing import Process # Manager is a class that provides a mechanism for data sharing. It provides many data types: 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'] = 0 from 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}) # shared data 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)