You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何使用Semaphore的多进程程序耗时20秒而非预期10秒,如何修复

问题原因
  • 错误出在进程启动与等待的逻辑顺序:现有代码每启动一个进程就立即调用join()方法阻塞主进程,必须等当前进程执行结束才会启动下一个进程,四个进程完全串行运行,Semaphore的并发控制逻辑没有生效,最终总耗时为4*5=20秒。
修复方案

将join()操作移到所有进程全部启动完成之后再执行:

import time
from multiprocessing import Semaphore, Process

def test(sem):
    sem.acquire()
    time.sleep(5)
    sem.release()

if __name__ == '__main__':
    sem = Semaphore(2)
    processes = []
    
    for _ in range(4):
        processes.append(Process(target=test, args=(sem,)))

    start = time.perf_counter()
    
    # 先启动所有进程
    for process in processes:
        process.start()
    # 所有进程启动完成后,再统一等待全部进程执行结束
    for process in processes:
        process.join()

    end = time.perf_counter() - start

    print(f'program finished in {end} secs')

修复后运行输出示例:

program finished in 10.0723491 secs
[Finished in 10.3s]

内容的提问来源于stack exchange,提问作者henry tjhia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 03:27:00