为什么当fork()的父进程在fork之前放入队列时,multiprocessing.Queue会卡住?

问题描述 投票:0回答:1

我最近写了这个程序:

import os, time
from multiprocessing import Queue

q = Queue(1000)

q.put(1)     # Line 6

result = os.fork()
if result == 0:
    while True:
        q.put(2)
        time.sleep(1)
elif result > 0:
    while True:
        print(q.get())
else:
    raise Exception('Fork failed: %d' % result)

程序使用

os.fork()
创建子进程。子进程不断地向队列发送
2
,父进程不断地从队列中读取。

我期望看到“1 2 2 2 2 2 ...”作为输出(这里我折叠行以简洁),但实际上我只看到“1”并且程序卡住了。是不是陷入了僵局?是我做错了什么,还是Python的bug

multiprocess.Queue

如果删除第 6 行,则输出为“2 2 2 ...”,这是预期的。

注意:我在 stackoverflow 上看到一些相关问题提到在退出前调用

Queue.join_thread()
。但是,我的程序没有这个问题,因为没有进程退出。

如果相关的话,我在 Linux 上使用 Python 3.11.2 。我也尝试过Python 3.9.18 .

python multiprocessing fork
1个回答
0
投票

我尝试了Python 3.12和Python 3.13(rc),运行程序时收到警告,这解决了谜团:

a.py:10: DeprecationWarning: This process (pid=1234) is multi-threaded, use of fork() may lead to deadlocks in the child.
  result = os.fork()

因此,放入

Queue
会创建一个新线程,然后调用
os.fork()
会导致死锁。

© www.soinside.com 2019 - 2024. All rights reserved.