博客
关于我
Python multiprocessing.Queue 与 multiprocessing.manager().Queue()
阅读量:803 次
发布时间:2023-03-06

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

Python中的multiprocessing模块提供了两种不同的Queue类,分别是通过Manager获取的Queue以及直接从模块导入的Queue。两者在数据共享和进程间通信方式上存在显著差异,适用于不同场景。

1. multiprocessing.Manager().Queue()

Manager().Queue()是一个分布式队列,主要用于多进程之间的数据共享和通信。在需要多个进程共享数据时非常有用。以下是一个使用Manager获取Queue的示例:

from multiprocessing import Process, Managerimport timedef add_to_queue(q):    for i in range(5):        print('Adding %s to queue' % i)        q.put(i)        time.sleep(0.1)manager = Manager()task_queue = manager.Queue()p = Process(target=add_to_queue, args=(task_queue,))p.start()p.join()while not task_queue.empty():    print('Got %s from queue' % task_queue.get())

2. multiprocessing.Queue

Directly imported Queue是一个本地队列,主要用于简单的多进程通信。在只需多进程之间进行简单通信时非常方便。以下是一个使用直接Queue的示例:

from multiprocessing import Process, Queueimport timedef add_to_queue(q):    for i in range(5):        print('Adding %s to queue' % i)        q.put(i)        time.sleep(0.1)task_queue = Queue()p = Process(target=add_to_queue, args=(task_queue,))p.start()p.join()while not task_queue.empty():    print('Got %s from queue' % task_queue.get())

测试用例

  • 对于Manager().Queue(),可以尝试在多个不同进程间添加和获取数据。
  • 对于Queue(),可以尝试在同一个进程内添加和获取数据。

应用场景

在大数据处理和机器学习任务中,通常需要多个进程来并行计算和处理数据。此时,Manager().Queue()提供了方便的数据共享和通信机制。而对于简单的多进程通信,直接使用Queue同样高效。

转载地址:http://ioafk.baihongyu.com/

你可能感兴趣的文章
Python selenium自动化测试框架实战 —— 登录测试案例
查看>>
Python Selenium设计模式 —— POM
查看>>
Python Serial:如何使用 read 或 readline 函数一次读取多个字符
查看>>
Python set([]) 如何检查两个对象是否相等?一个对象需要定义哪些方法来自定义它?
查看>>
Python setup.py:数据文件无法复制目录:不存在或不是常规文件
查看>>
Python setuptools sdist:仅安装版本化文件
查看>>
Python Shell下使用matplotlib
查看>>
Python Slice How-to,我知道Python Slice,但我怎么才能使用内置的Slice对象呢?
查看>>
python socket分包发送数据
查看>>
python socket模块_Python socket模块实现TCP服务端客户端
查看>>
Python SOCKS5代理客户端HTTPS
查看>>
Python Soc网络分析:通过使用函数迭代列表来计算机会网络
查看>>
python转换已转义的字符串
查看>>
Python Sphinx自动摘要:成员函数的自动列表
查看>>
Python SQL和NoSQL数据库操作实战
查看>>
python stdout flush_sys.stdout.flush()方法的用法
查看>>
python string 运算
查看>>
Python str与bytes之间的转换
查看>>
Python subprocess ffmpeg
查看>>
python subprocess Permission denied Errno 13
查看>>