python / python/cpython

On Windows, creating a multiprocessing pool leaks handles

未关闭
#154,208 5 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

OS-windows stdlib topic-multiprocessing type-bug
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Example:

import ctypes.wintypes
import gc
import multiprocessing.pool

kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

kernel32.GetCurrentProcess.argtypes = ()
kernel32.GetCurrentProcess.restype = ctypes.wintypes.HANDLE

kernel32.GetProcessHandleCount.argtypes = (ctypes.wintypes.HANDLE, ctypes.wintypes.LPDWORD)
kernel32.GetProcessHandleCount.restype = ctypes.wintypes.BOOL

def handle_count():
    # Pseudo-handle that doesn't need to be closed
    hproc = kernel32.GetCurrentProcess()

    handle_count = ctypes.wintypes.DWORD()
    if not kernel32.GetProcessHandleCount(hproc, ctypes.byref(handle_count)):
        raise ctypes.WinError(ctypes.get_last_error())

    return handle_count.value

def func():
    pool = multiprocessing.pool.Pool(1)
    pool.terminate()
    pool.join()
    pool.close()
    pool = None
    gc.collect()

def main():
    print("Initial handle count:", handle_count())
    for _ in range(4):
        func()
        print("Handle count:", handle_count())

if __name__ == "__main__":
    main()

Output with Python 3.16 on Windows:

Initial handle count: 116
Handle count: 123
Handle count: 127
Handle count: 131
Handle count: 135

I discovered the issue while working on PR gh-154140 which detects leaks of Windows handles in the Python test suite.

Linked PRs
  • gh-154365

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

先在 Windows 上复现 main() 和 func(),然后跟踪 multiprocessing.pool.Pool 的创建和终止,以确定哪些句柄仍处于打开状态。查看链接的 gh-154365 以及 gh-154140 中的句柄泄漏背景。完成标准是:重复创建池不再增加报告的进程句柄数量。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
operating-systems
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。