gpt4 book ai didi

python - 使用 python(windows) 创建两个子进程

转载 作者:行者123 更新时间:2023-11-28 21:44:27 25 4
gpt4 key购买 nike

使用Python编程语言完成以下任务:

创建两个进程(我们称它们为 P1 和 P2)。 P1 应该打印“我是 P1”,P2 应该打印“我是 P2”。主进程(创建 P1 和 P2 的进程)应该等待它们。然后,P1和P2完成后,主进程应该打印“我是主进程,两个进程都完成了”。

最佳答案

在 Windows 中,我们没有 fork 系统调用,所以我们可以使用一个名为 multiprocessing 的 python 模块:-

from multiprocessing import Process, Lock
import time
import os
def f(lock,id,sleepTime):
lock.acquire()
print "I'm P"+str(id)+" Process ID: "+str(os.getpid())
lock.release()
time.sleep(sleepTime) #sleeps for some time

if __name__ == '__main__':
print "Main Process ID: "+str(os.getpid())
lock=Lock()
p1=Process(target=f, args=(lock,1,3,)) #P1 sleeps for 3 seconds
p2=Process(target=f, args=(lock,2,5,)) #P2 sleeps for 5 seconds
start=time.time()
p1.start()
p2.start()
p1.join()
p2.join()
end=time.time()
print "I am the main process, the two processes are done"
print "Time taken:- "+str(end-start)+"secs" #MainProcess terminates at approx ~ 5 secs.

任务管理器中捕获的进程:- P1,P2 and Main Process代码输出是:-

Main Process ID: 9804
I'm P1 Process ID: 6088
I'm P2 Process ID: 4656
I am the main process, the two processes are done
Time taken:- 5.15300011635secs

希望对您有所帮助!!

关于python - 使用 python(windows) 创建两个子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40690364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com