プロセス関数 (例: 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