简体   繁体   English

multiprocessing 是否正常工作?

[英]Does multiprocessing work like this normally?

Source Code源代码

import multiprocessing
import time


inTime = time.time()
def sleeper():
    print("Im sleeper")
    time.sleep(1)

if __name__ == "__main__":
    p1 = multiprocessing.Process(sleeper())
    p1.start()
    p1.join()
    p2 = multiprocessing.Process(sleeper())
    p2.start()
    p2.join()

    nTime = time.time()
    print(f"done in {round(nTime-inTime,2)} s")

I'm not getting it to work as expected.我没有让它按预期工作。 It must complete the process within 1s but it takes 2s queuing one function after another.它必须在 1s 内完成该过程,但需要 2s 排队一个 function 一个接一个。 I'm running it on Python 3.11.1 [64bit]我在 Python 3.11.1 [64 位] 上运行它

You have three problems.你有三个问题。 First, you call sleeper() and then create a process that does nothing.首先,您调用sleeper()然后创建一个什么都不做的进程。 Second, you join the first process before even starting the second.其次,您甚至在开始第二个流程之前就加入了第一个流程。 Third, the target subprocess function should be in the target parameter.第三,目标子进程function应该在target参数中。 To get things to go in parallel, you can do要并行处理 go,您可以这样做

import multiprocessing
import time

inTime = time.time()
def sleeper():
    print("Im sleeper")
    time.sleep(1)

if __name__ == "__main__":
    p1 = multiprocessing.Process(target=sleeper)
    p1.start()
    p2 = multiprocessing.Process(target=sleeper)
    p2.start()
    p1.join()
    p2.join()

    nTime = time.time()
    print(f"done in {round(nTime-inTime,2)} s")

Output Output

Im sleeper
Im sleeper
done in 1.01 s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM