doutangliang7769
doutangliang7769
2018-12-22 06:30

为什么Python的multiprocessing.Queue不会阻塞

  • python
  • channel
  • multiprocessing

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:
        time.sleep(1)
        print("Put")
        q.put("hello world")


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

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 (
    "fmt"
    "time"
)

func main() {
    ch := make(chan int)
    for {
        time.Sleep(time.Second)
        fmt.Println("Put")
        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条回答

为你推荐