前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python JoinableQueue在生产者消费者项目中的简单应用

python JoinableQueue在生产者消费者项目中的简单应用

作者头像
Ryan_OVO
发布2023-10-19 19:17:04
1730
发布2023-10-19 19:17:04
举报
文章被收录于专栏:程序随笔

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 a task_done() call was received for every item that had been put() 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如下:

代码语言:javascript
复制
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)

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-04-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档