2018-12-22 06:30 阅读 450


I am new to Python, but I want to write a multiproccesing program that uses multiprocessing.Queue as Go's channel. However, it seems that multiprocessing.Queue.put(, block=True) doesn't block as documented.

Here is my Python example program:

import multiprocessing
import select
import time

def f(q):
    while True:
        q.put("hello world")

if __name__ == "__main__":
    q = multiprocessing.Queue(maxsize=0)

I expect that it will print only one "Put" and blocks forever. However, what I got is that it prints "Put" repeatedly.

Here is the Go program I think almost equivalent, except that goroutine is a green thread but not a process.

package main

import (

func main() {
    ch := make(chan int)
    for {
        ch <- 1

When I type go run csp.go, it prints only one "Put" and the Go runtime prompts that the program is in deadlock.

Why multiprocessing.Queue.put() doesn't block?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duansha7453 duansha7453 2018-12-22 06:42

    Give a queue length of 1 and it will block as required

       Python 2.7.12 (default, Nov 12 2018, 14:36:49) 
        [GCC 5.4.0 20160609] on linux2
        Type "help", "copyright", "credits" or "license" for more information.
        >>> import multiprocessing
        >>> import select
        >>> import time
        >>> q = multiprocessing.Queue(maxsize=1)
        >>> q.put(9)
        >>> q.put(10)  // blocking here, have to ctrl-c to escape
        ^CTraceback (most recent call last):
          File "<stdin>", line 1, in <module>
          File "/usr/lib/python2.7/multiprocessing/", line 101, in put
            if not self._sem.acquire(block, timeout):
    点赞 评论 复制链接分享