gpt4 book ai didi

python - 如何使用多处理模块终止进程?

转载 作者:太空宇宙 更新时间:2023-11-03 10:49:01 24 4
gpt4 key购买 nike

我有一个本质上只是一个无限循环的进程,我还有一个计时器进程。计时器完成后如何终止循环进程?

def action():
x = 0
while True:
if x < 1000000:
x = x + 1
else:
x = 0

def timer(time):
time.sleep(time)
exit()

loop_process = multiprocessing.Process(target=action)
loop_process.start()
timer_process = multiprocessing.Process(target=timer, args=(time,))
timer_process.start()

我希望 python 脚本在计时器完成后结束。

最佳答案

您可以使用 sharing state between the processes 来完成并创建一个所有并发进程都可以访问的标志值(尽管这可能有点低效)。

这是我的建议:

import multiprocessing as mp
import time

def action(run_flag):
x = 0
while run_flag.value:
if x < 1000000:
x = x + 1
else:
x = 0

print('action() terminating')


def timer(run_flag, secs):
time.sleep(secs)
run_flag.value = False


if __name__ == '__main__':

run_flag = mp.Value('I', True)

loop_process = mp.Process(target=action, args=(run_flag,))
loop_process.start()

timer_process = mp.Process(target=timer, args=(run_flag, 2.0))
timer_process.start()

loop_process.join()
timer_process.join()

print('done')

关于python - 如何使用多处理模块终止进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54929482/

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