gpt4 book ai didi

python - 如何随后运行两个并行进程?

转载 作者:太空宇宙 更新时间:2023-11-04 09:02:05 25 4
gpt4 key购买 nike

我想确保以下两个并行过程相继实现。特别是,我希望先实现十个 f 功能,然后在完成该部分后,再实现十个 g 功能。有谁知道我应该如何修改我的代码?

from multiprocessing import Process
import time
import random

wait_low = 0.1
wait_high = 15

def f(i):
time.sleep(random.uniform(wait_low, wait_high))
print 'hello'+str(i)

def g(i):
time.sleep(random.uniform(wait_low, wait_high))
print 'hey'+str(i)


if __name__ == '__main__':
for j in range(10):
p = Process(target=f, args=(j,))
p.start()
p.join()

print "switch"

# comment
for j in range(10):
q = Process(target=g, args=(j,))
q.start()
q.join()

time.sleep(5)

print "I'm done"

我得到的结果是:

hello2
hello0
hello1
hello5
hello6
hello8
hello3
hello7
hello9
switch
hey6
hey3
hello4
hey9
hey8
I'm done
hey2
hey0
hey1
hey5
hey7
hey4

非常感谢!

最佳答案

所有 fg 都需要连接。

if __name__ == '__main__':
fs = []
for j in range(10):
p = Process(target=f, args=(j,))
p.start()
fs.append(p)

for f in fs:
f.join()

print "switch"

# comment
gs = []
for j in range(10):
q = Process(target=g, args=(j,))
q.start()
gs.append(q)

for g in gs:
g.join()

print "I'm done"

输出:

hello2
hello8
hello5
hello6
hello9
hello1
hello4
hello3
hello7
hello0
switch
hey0
hey7
hey2
hey8
hey4
hey3
hey1
hey9
hey5
hey6
I'm done

关于python - 如何随后运行两个并行进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24195923/

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