【10.10】进程间通信--Queue、Pipe、Manager

利用Queue,这个Queue不是queue里面的

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 from multiprocessing import Process, Queue
 5 import time
 6 
 7 
 8 def producer(queue):
 9     queue.put('a')
10     time.sleep(2)
11 
12 
13 def consumer(queue):
14     time.sleep(2)
15     data = queue.get()
16     print(data)
17 
18 
19 if __name__ == '__main__':
20     queue = Queue(10)
21     my_producer = Process(target=producer, args=(queue,))
22     my_consumer = Process(target=consumer, args=(queue,))
23     my_producer.start()
24     my_consumer.start()
25     my_producer.join()
26     my_consumer.join()
a

 共享全局变量不能适用于多进程编程,只能用于多线程编程

multiprocessing里面的Queue不能用于pool进程池,但是multiprocessing里面有一个Manager

 1 from multiprocessing import Process, Queue, Manager, Pool
 2 import time
 3 
 4 
 5 def producer(queue):
 6     queue.put('a')
 7     time.sleep(2)
 8 
 9 
10 def consumer(queue):
11     time.sleep(2)
12     data = queue.get()
13     print(data)
14 
15 
16 if __name__ == '__main__':
17     pool = Pool(2)
18     queue = Manager().Queue(10)
19 
20     pool.apply_async(producer, args=(queue,))
21     pool.apply_async(consumer, args=(queue,))
22 
23     pool.close()
24     pool.join()
a

 pool中的进程间通信用manager中的Queue

pipe

 1 # 通过pipe实现进程间通信
 2 # pipe的性能高于queue
 3 from multiprocessing import Pipe, Pool, Process
 4 import time
 5 
 6 
 7 def producer(pipe):
 8     pipe.send('zy')
 9     time.sleep(2)
10 
11 
12 def consumer(pipe):
13     print(pipe.recv())
14 
15 
16 if __name__ == '__main__':
17     pool = Pool(2)
18     # pipe只能适用于两个进程间的通信
19     recevie_pipe, send_pipe = Pipe()
20     my_producer = Process(target=producer, args=(send_pipe,))
21     my_consumer = Process(target=consumer, args=(recevie_pipe,))
22 
23     my_producer.start()
24     my_consumer.start()
25 
26     my_producer.join()
27     my_consumer.join()
zy

还有manager中共享的数据结构。。。

原文地址:https://www.cnblogs.com/zydeboke/p/11310186.html