博客
关于我
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 subprocess ffmpeg
查看>>
python subprocess Permission denied Errno 13
查看>>
Python subprocess.call - 将变量添加到 subprocess.call
查看>>
Python Subprocess.Popen 从一个线程
查看>>
Python subprocess.Popen 作为 Windows 上的不同用户
查看>>
Python转换PPT为PDF
查看>>
Python subprocess.Popen() 等待完成
查看>>
Python sum 二维列表中具有相同第一个值的元素
查看>>
Python Sympy模块NoConversion:收敛到根失败;请尝试n<;15或MaxSteps>;50
查看>>
Python sys.MODULES包含尚未导入的模块
查看>>
python sys模块使用
查看>>
Python tarfile、zipfile解压模块讲解
查看>>
python tcp server传输成功之后进行删除_python学习之路(三)使用socketserver进行ftp断点续传...
查看>>
python车牌识别系统+车辆管理+计费系统(图像识别)django框架 计算机毕业设计
查看>>
Python threading.Thread 只能使用私有方法 self.__Thread_stop() 停止
查看>>
python time模块
查看>>
Python Tkinter Multiple Windows 教程
查看>>
Python tkinter 中的多处理
查看>>
python tkinter 按钮颜色_Python3 tkinter基础 Button bg 按钮的背景颜色
查看>>
Python Tkinter 笔记本小部件
查看>>