博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python JoinableQueue在生产者消费者项目中的简单应用
阅读量:6331 次
发布时间:2019-06-22

本文共 1757 字,大约阅读时间需要 5 分钟。

class multiprocessing.JoinableQueue([maxsize])

, a  subclass, is a queue which additionally has  and  methods.

task_done
()

Indicate that a formerly enqueued task is complete. Used by queue consumers. For each  used to fetch a task, a subsequent call to tells the queue that the processing on the task is complete.

If a  is currently blocking, it will resume when all items have been processed (meaning that a  call was received for every item that had been  into the queue).

Raises a  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  to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero,  unblocks.

 

这是官网对JoinableQueue的概述,我们通过这个方法就可以实现我们自己的生产者消费者模型,具体的实现思路请看我的分析<<>>

code如下:

import multiprocessingdef 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)

 

简单地实现了我要的结果,具体可以再项目中应用上。

转载于:https://www.cnblogs.com/zhiyong-ITNote/p/8778052.html

你可能感兴趣的文章
Python之Paramiko、前端之html学习_Day14
查看>>
HDU 3836 Equivalent Sets
查看>>
深入理解JVM读书笔记思维导图
查看>>
String字符串位置移动
查看>>
MySQL无法插入中文的解决方案
查看>>
react16 渲染流程
查看>>
Android游戏与应用开发最佳学习路线图
查看>>
Android应用打开外部文件
查看>>
hadoop生态搭建(3节点)-05.mysql配置_单节点
查看>>
堆和栈的区别
查看>>
网易2017春招笔试真题编程题集合(2)——赶去公司
查看>>
top命令
查看>>
JS-键盘事件之方向键移动元素
查看>>
Compass(更新中。。。)
查看>>
bos开发时,测试卡在登录界面解决
查看>>
2013 Multi-University Training Contest 2
查看>>
ubuntu开机自动运行用Qt写的程序
查看>>
关于JSON的一些问题
查看>>
WebShell代码分析溯源(第1题)
查看>>
log4j的日志级别(ssm中log4j的配置)
查看>>