multiprocessing race condition on flushing stdout, deadlocks child on exit
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 36k
- PR 合并指标
- PR 指标待抓取
描述
I experienced deadlocks when using the logging example for multiprocessing, where a QueueHandler is used.
I found that sometimes a multiprocessing process is not terminating, when it has put an element in a Queue,
even if the parent process runs a thread to empty the queue and successfully retrieved the item.
The worker looks like this:
def worker(q):
q.put(current_process().name)
return
and while this works:
workers = []
for i in range(15):
p = Process(target=worker, args=(logq,), name=f"Worker {i+1}")
workers.append(p)
for p in workers:
p.start()
time.sleep(.1)
removing the sleep leads to a very high propability of deadlocking when I then try to join the processes, e.g,:
for w in workers:
print(f'trying to join on {w.name}, alive={w.is_alive()}, exitcode={w.exitcode}', w.name, w.is_alive(), w.exitcode)
w.join()
The Process is still marked as alive, hitting Ctrl+C gives this:
trying to join on Worker 14, alive=True, exitcode=None Worker 14 True None
^CTraceback (most recent call last):
File "/home/fls/pybug/deadlock.py", line 43, in <module>
w.join()
File "/usr/lib/python3.10/multiprocessing/process.py", line 149, in join
res = self._popen.wait(timeout)
File "/usr/lib/python3.10/multiprocessing/popen_fork.py", line 43, in wait
return self.poll(os.WNOHANG if timeout == 0.0 else 0)
File "/usr/lib/python3.10/multiprocessing/popen_fork.py", line 27, in poll
pid, sts = os.waitpid(self.pid, flag)
KeyboardInterrupt
Can reproduce using Python 3.9.10 and 3.10.4 on Linux:
import time
import threading
from multiprocessing import Process, Queue, current_process
def logger_thread(q: Queue):
while True:
record = q.get()
if record is None:
break
print("logrecord: ", record)
def worker(q):
q.put(current_process().name)
return
logq = Queue()
lp = threading.Thread(target=logger_thread, args=(logq,), daemon=True)
lp.start()
workers = []
for i in range(15):
p = Process(target=worker, args=(logq,), name=f"Worker {i+1}")
workers.append(p)
print("starting workers")
for p in workers:
p.start()
# no deadlock when added:
# time.sleep(.1)
print("waiting a bit")
time.sleep(1)
print("trying to join workers")
for w in workers:
print(f'trying to join on {w.name}, alive={w.is_alive()}, exitcode={w.exitcode}', w.name, w.is_alive(), w.exitcode)
w.join()
print(f'joined on {w.name}', w.name)
logq.put(None)
lp.join()
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
首先,在 Linux 上使用报告中的 Python 版本运行所提供的 multiprocessing 复现,然后检查 multiprocessing Queue 和子进程退出路径,包括 traceback 中显示的 multiprocessing/process.py 和 multiprocessing/popen_fork.py 路径。完成的标准是:Queue 项目被取出后,worker 能够可靠地 join,并且针对已复现案例具有回归测试覆盖。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- distributed-systems
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 需要澄清
- 新手友好度
- 35/100