python队列和多处理队列: how they behave?

标签 python queue

这个示例代码有效(我可以在文件中写一些东西):

from multiprocessing import Process, Queue

queue = Queue()
def _printer(self, queue):
    queue.put("hello world!!")

def _cmdDisp(self, queue):
    f = file("Cmd.log", "w")
    print >> f, queue.get()
    f.close()

而不是这个其他示例:(errormsg: 'module' object is not callable)

import Queue

queue = Queue()
def _printer(self, queue):
    queue.put("hello world!!")

def _cmdDisp(self, queue):
    f = file("Cmd.log", "w")
    print >> f, queue.get()
    f.close()

这不是其他示例(我无法在文件中写入内容):

import Queue

queue = Queue.Queue()
def _printer(self, queue):
    queue.put("hello world!!")

def _cmdDisp(self, queue):
    f = file("Cmd.log", "w")
    print >> f, queue.get()
    f.close()

有人可以解释这些差异吗?以及做事的权利?

最佳答案

对于你的第二个例子,你自己已经给出了解释---Queue是一个模块,不能被调用。

对于第三个示例:我假设您将 Queue.Queuemultiprocessing 一起使用。 Queue.Queue 不会在进程之间共享。如果 Queue.Queue 在进程之前声明,那么每个进程都会收到它的副本,然后该副本独立于其他所有进程。在启动子代之前,父代放置在 Queue.Queue 中的项目将可供每个子代使用。 Queue.Queue 在启动子进程后由父进程放置的项目将只对父进程可用。 Queue.Queue 用于同一进程内不同线程 之间的数据交换(使用threading 模块)。多处理队列用于不同 Python 进程之间的数据交换。虽然 API 看起来很相似(就是这样设计的),但底层机制却有着根本的不同。

  • multiprocessing 队列通过腌制(序列化)对象并通过管道发送它们来交换数据。
  • Queue.Queue 使用在线程和锁/互斥锁之间共享的数据结构以实现正确的行为。

关于python队列和多处理队列: how they behave?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/925100/

相关文章:

python - 如何一次对列表中的 2 个随机元素运行循环?

python - 如何使用 numpy 获得两个矩阵的点积?

python - 为什么 Ruby 和 Python 比 Groovy 更适合在 IDE 之外进行编程?

c# - "Due to heavy load, the latest workflow operation has been queued"--> 如何查看队列?

Java - 在删除/获取上排序的线程安全集合

python - 从 2 个单独的列表中提取信息

python - 如何从列表中的字符串中删除前 x 个字符

multithreading - 简单队列模型示例

linux - 如何使用 <sys/queue.h> 功能对列表进行排序?

c++ - 从后到前显示用链表实现的队列