为什么 Python 的 multiprocessing.Queue 不阻塞

我是 Python 的新手,但我想编写一个用作multiprocessing.QueueGo 通道的多进程程序。但是,似乎并multiprocessing.Queue.put(, block=True)没有像记录的那样阻止。


这是我的 Python 示例程序:


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)

我希望它只会打印一个“Put”并永远阻塞。但是,我得到的是它反复打印“Put”。


这是我认为几乎等效的 Go 程序,只是 goroutine 是一个绿色线程而不是进程。


package main


import (

    "fmt"

    "time"

)


func main() {

    ch := make(chan int)

    for {

        time.Sleep(time.Second)

        fmt.Println("Put")

        ch <- 1

    }

}

当我键入 时go run csp.go,它只打印一个“Put”,Go 运行时提示程序处于死锁状态。


为什么multiprocessing.Queue.put()不阻止?


红颜莎娜
浏览 71回答 1
1回答

临摹微笑

队列长度为 1,它会根据需要阻塞&nbsp; &nbsp;Python 2.7.12 (default, Nov 12 2018, 14:36:49)&nbsp;&nbsp; &nbsp; [GCC 5.4.0 20160609] on linux2&nbsp; &nbsp; Type "help", "copyright", "credits" or "license" for more information.&nbsp; &nbsp; >>> import multiprocessing&nbsp; &nbsp; >>> import select&nbsp; &nbsp; >>> import time&nbsp; &nbsp; >>>&nbsp;&nbsp; &nbsp; >>> q = multiprocessing.Queue(maxsize=1)&nbsp; &nbsp; >>> q.put(9)&nbsp; &nbsp; >>> q.put(10)&nbsp; // blocking here, have to ctrl-c to escape&nbsp; &nbsp; ^CTraceback (most recent call last):&nbsp; &nbsp; &nbsp; File "<stdin>", line 1, in <module>&nbsp; &nbsp; &nbsp; File "/usr/lib/python2.7/multiprocessing/queues.py", line 101, in put&nbsp; &nbsp; &nbsp; &nbsp; if not self._sem.acquire(block, timeout):&nbsp; &nbsp; KeyboardInterrupt&nbsp; &nbsp; >>>&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP