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

Python Multiprocessing问题:启动进程后后续代码无法执行,求解决方案

问题描述

刚掌握Python Threading,正在学习Multiprocessing。编写了一个简单定时器程序:每秒递增计数,直到用户在控制台按下回车键终止。Threading版本可正常运行,但改用Multiprocessing实现时,启动进程后后续代码始终无法执行。已尝试修正target参数的括号问题(将timer()改为timer),但问题依旧,寻求解决思路。

问题代码

import multiprocessing
import time

done = False


def timer():
    counter = 0
    while not done:
        time.sleep(1)
        counter += 1
        print(counter)


if __name__ == '__main__':
    p1 = multiprocessing.Process(target=timer())
    p1.start()
    # 这段代码永远不会执行,用线程时正常
    input("Press enter to quit")
    done = True
解决思路
  • 修正target参数错误:你当前代码里的target=timer()是直接执行了timer函数,而非传递函数对象。这会导致主进程在创建子进程前就进入timer的死循环,后续代码完全无法运行。必须改成target=timer,同时通过args参数传递所需参数。
  • 解决多进程全局变量不共享问题:多进程拥有独立的内存空间,主进程修改全局变量done的取值不会同步到子进程。要实现状态共享,需使用multiprocessing提供的共享内存对象,比如Value:
    修正后的示例代码:
    import multiprocessing
    import time
    
    def timer(done):
        counter = 0
        while not done.value:
            time.sleep(1)
            counter += 1
            print(counter)
    
    
    if __name__ == '__main__':
        # 创建布尔型共享变量,初始值为False
        done = multiprocessing.Value('b', False)
        # 传递函数对象和共享变量作为参数
        p1 = multiprocessing.Process(target=timer, args=(done,))
        p1.start()
        input("Press enter to quit")
        # 修改共享变量的值,子进程会感知到变化
        done.value = True
        # 等待子进程正常结束
        p1.join()
    
  • 核心区别提醒:线程共享同一进程的内存空间,因此全局变量可直接传递状态;而多进程是完全独立的执行单元,必须通过IPC(进程间通信)机制(如共享内存、队列、管道)来同步状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 06:47:08