如果您的流程函数(例如submit_process
)有一个循环,您可以在其中测试条件,您可以为此使用 mp.Event:
import multiprocessing as mp
import time
import logging
logger = mp.log_to_stderr(logging.DEBUG)
logger.setLevel(logging.INFO)
def submit_process(i, sig):
logger.info("submit_process")
while True:
#Here is some codes trying to change the value of the variable sig
if i == 0:
time.sleep(2)
sig.set()
logger.info('SETTING sig')
time.sleep(1)
if sig.is_set():
#Here i want to exit the entire program instead of the single thread only.
#exit(0)
logger.info('sig is set!')
break
else:
logger.info('sig is NOT set!')
process_list = []
logger.info("OK")
sig = mp.Event()
for i in range(3):
process = mp.Process(target = submit_process, args = (i, sig, ))
process.start()
process_list.append(process)
for i in range( len(process_list) ):
process_list[i].join()
产量
[INFO/MainProcess] OK
[INFO/Process-2] child process calling self.run()
[INFO/Process-2] submit_process
[INFO/Process-3] child process calling self.run()
[INFO/Process-1] child process calling self.run()
[INFO/Process-3] submit_process
[INFO/Process-1] submit_process
[INFO/Process-2] sig is NOT set!
[INFO/Process-3] sig is NOT set!
[INFO/Process-2] sig is NOT set!
这里 process-1 设置 mp.Event:
[INFO/Process-1] SETTING sig
在这里,进程识别出 sig 已设置并跳出 while 循环:
[INFO/Process-3] sig is set!
[INFO/Process-3] process shutting down
[INFO/Process-3] process exiting with exitcode 0
[INFO/Process-2] sig is set!
[INFO/Process-2] process shutting down
[INFO/Process-2] process exiting with exitcode 0
[INFO/Process-1] sig is set!
[INFO/Process-1] process shutting down
[INFO/Process-1] process exiting with exitcode 0
[INFO/MainProcess] process shutting down