栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Python中使用多处理队列?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Python中使用多处理队列?

我的主要问题是我真的不知道如何正确实现multiprocessing.queue,您不能为每个进程真正实例化对象,因为它们将是单独的队列,如何确保所有进程都与共享队列相关(或在这种情况下,排队)

这是读取器和写入器共享一个队列的简单示例。写入器向读取器发送一堆整数。当写入器的数字用完时,它将发送“ DONE”(完成),让读取器知道退出读取循环。

from multiprocessing import Process, Queueimport timeimport sysdef reader_proc(queue):    ## Read from the queue; this will be spawned as a separate Process    while True:        msg = queue.get()         # Read from the queue and do nothing        if (msg == 'DONE'): breakdef writer(count, queue):    ## Write to the queue    for ii in range(0, count):        queue.put(ii)  # Write 'count' numbers into the queue    queue.put('DONE')if __name__=='__main__':    pqueue = Queue() # writer() writes to pqueue from _this_ process    for count in [10**4, 10**5, 10**6]:          ### reader_proc() reads from pqueue as a separate process        reader_p = Process(target=reader_proc, args=((pqueue),))        reader_p.daemon = True        reader_p.start()        # Launch reader_proc() as a separate python process        _start = time.time()        writer(count, pqueue)    # Send a lot of stuff to reader()        reader_p.join()         # Wait for the reader to finish        print("Sending {0} numbers to Queue() took {1} seconds".format(count,  (time.time() - _start)))


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/646823.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号