使用多处理.join()未阻止执行

2024-09-30 06:20:59 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我运行的一些代码。我试图确保在继续我的代码之前,我的所有进程都完成了,但这并没有像我期望的那样发生。你知道吗

import sys
import multiprocessing as mp
import time
import random

def testJoin(argin):
    name =  mp.current_process().name
    exStartTime = time.time()
    time.sleep(argin * random.random())
    print(name + ' took %d seconds' %(time.time() - exStartTime))
    sys.stdout.flush()


if __name__ == '__main__':
    instances = [10, 10, 10, 10]
    jobs = []
    for k in instances:
        p = mp.Process(target = testJoin, args = (k,))
        jobs.append(p)
        p.start()
    p.join()

print('End of Program')

以下是输出内容:

End of Program
Process-4 took 1 seconds
End of Program
End of Program
Process-2 took 4 seconds
End of Program
Process-1 took 9 seconds
End of Program
Process-3 took 9 seconds

我感到困惑的是,我不希望看到“程序结束”打印不止一次,我当然不希望看到它打印,直到我的四个进程都结束。我错过了什么?你知道吗


Tags: of代码nameimporttime进程sysrandom
1条回答
网友
1楼 · 发布于 2024-09-30 06:20:59

您描述的行为在Unix下不会发生,但在Windows下会发生。 Windows缺少os.fork,所以为了启动子进程,multiprocessing starts a new Python interpreter and imports the calling module。你知道吗

导入时的if __name__ == "__main__"protects code from getting executed。自从

print('End of Program')

不在if-statement内,每次导入调用模块时执行一次,主进程执行一次。你知道吗

解决方案是将print调用放在if-statement中。你知道吗

相关问题 更多 >

    热门问题