met*_*met 5 python multiprocessing python-3.x python-multiprocessing
我有一个本质上只是一个无限循环的过程,我有第二个过程是一个计时器。计时器完成后如何终止循环进程?
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()
Run Code Online (Sandbox Code Playgroud)
我希望 python 脚本在计时器完成后结束。
您可以通过在进程之间使用共享状态并创建所有并发进程都可以访问的标志值来完成此操作(尽管这可能效率较低)。
这是我的建议:
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')
Run Code Online (Sandbox Code Playgroud)