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

Python多进程中notworking()函数无法运行的问题求助

问题解决:让multiprocessing中notworking()函数正常运行

你的代码存在两个关键问题,导致notworking()函数无法执行:

  1. Process的target参数传错了
    你写的target=whyisthis()是直接调用函数,而不是传递函数对象。whyisthis()是无限循环,主线程会卡在这个函数的执行里,根本没机会创建并启动第二个进程。

  2. 缺少time模块导入
    代码里用了time.sleep()但没导入time模块,运行会报错。

修正后的代码如下:

import time
from multiprocessing import Process

def whyisthis():
    while True:
        print(f'Why is this')
        time.sleep(5)

def notworking():
    while True:
        print(f'not working')
        time.sleep(5)  # 可选:加上sleep避免打印过快刷屏

if __name__ == '__main__':
    # target传函数对象,不要加括号调用
    p1 = Process(target=whyisthis, daemon=False, name='Why is this')
    p2 = Process(target=notworking, daemon=False, name='Not working')
    
    p1.start()
    p2.start()
    p1.join()
    p2.join()

关键修正点说明:

  • 把target=whyisthis()改为target=whyisthis,target=notworking()改为target=notworking,让Process明确要执行的函数对象,而非先执行函数再传递结果。
  • 补充import time,修复模块未导入的错误。
  • 给notworking()添加time.sleep(5),优化控制台输出体验(可选)。

运行修正后的代码,两个进程会同时循环打印各自的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:15:43