python JoinableQueue在生产者消费者项目中的简…
2018-06-18 02:18:44来源:未知 阅读 ()
class multiprocessing.
JoinableQueue
([maxsize])
JoinableQueue
, a Queue
subclass, is a queue which additionally has task_done()
and join()
methods.
task_done
()-
Indicate that a formerly enqueued task is complete. Used by queue consumers. For each
get()
used to fetch a task, a subsequent call totask_done()
tells the queue that the processing on the task is complete.If a
join()
is currently blocking, it will resume when all items have been processed (meaning that atask_done()
call was received for every item that had beenput()
into the queue).Raises a
ValueError
if called more times than there were items placed in the queue.
join
()-
Block until all items in the queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer calls
task_done()
to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero,join()
unblocks.这是官网对JoinableQueue的概述,我们通过这个方法就可以实现我们自己的生产者消费者模型,具体的实现思路请看我的分析<<项目开发中使用并发模型常见问题的整理与思考>>
code如下:
import multiprocessing def printAll(queue, out_queue): while 1: t = queue.get() print(t) s = "生产{0}".format(t) queue.task_done() out_queue.put(s) if __name__ == "__main__": queue = multiprocessing.JoinableQueue() num_consumer = multiprocessing.cpu_count() * 2 out_queue = multiprocessing.Queue() for i in range(250): queue.put(i) for _ in range(num_consumer): p = multiprocessing.Process(target=printAll, args=(queue, out_queue)) p.start() queue.join() # 阻塞队列直到队列为空。 result = [] print("数量是: {}".format(out_queue.qsize())) while out_queue.qsize() != 0: result.append(out_queue.get()) for i in result: print(i)
简单地实现了我要的结果,具体可以再项目中应用上。
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- python3基础之“术语表(2)” 2019-08-13
- python3 之 字符串编码小结(Unicode、utf-8、gbk、gb2312等 2019-08-13
- Python3安装impala 2019-08-13
- 小白如何入门 Python 爬虫? 2019-08-13
- python_字符串方法 2019-08-13
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash