【10.10】进程间通信--Queue、Pipe、Manager
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了【10.10】进程间通信--Queue、Pipe、Manager,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1848字,纯文字阅读大概需要3分钟。
内容图文
利用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中共享的数据结构。。。
内容总结
以上是互联网集市为您收集整理的【10.10】进程间通信--Queue、Pipe、Manager全部内容,希望文章能够帮你解决【10.10】进程间通信--Queue、Pipe、Manager所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。