首页 > 解决方案 > ProcessPoolExecutor 工作人员具有相同的“线程 ID”?

问题描述

在使用多处理器池时查看线程 ID,发现它们都具有相同的线程 ID,但进程 ID 不同。使用线程池时,工作人员具有不同的线程 ID,但进程 ID 相同(如预期的那样),但我没想到在进程池中所有工作人员都具有相同的线程 ID。

def identify_self():
    import threading
    import os
    import time

    time.sleep(random())
    print(f"Thread={threading.get_ident()}, Process={os.getpid()}")
    time.sleep(3)


print("MP:")
with ProcessPoolExecutor(max_workers=10) as executor:
    for i in range(10):
        executor.submit(identify_self)


print("MT:")
with ThreadPoolExecutor(max_workers=10) as executor:
    for i in range(10):
        executor.submit(identify_self)

输出:

MP:
Thread=4584541632, Process=56989
Thread=4584541632, Process=56996
Thread=4584541632, Process=56998
Thread=4584541632, Process=56993
Thread=4584541632, Process=56990
Thread=4584541632, Process=56991
Thread=4584541632, Process=56992
Thread=4584541632, Process=56995
Thread=4584541632, Process=56997
Thread=4584541632, Process=56994
MT:
Thread=123145380663296, Process=56985
Thread=123145427959808, Process=56985
Thread=123145396428800, Process=56985
Thread=123145391173632, Process=56985
Thread=123145401683968, Process=56985
Thread=123145406939136, Process=56985
Thread=123145422704640, Process=56985
Thread=123145385918464, Process=56985
Thread=123145417449472, Process=56985
Thread=123145412194304, Process=56985

当 processpool 工作人员具有相同的 threadid 时,这意味着什么?它对 GIL 有影响吗?

标签: pythonmultithreading

解决方案


推荐阅读