Created
July 8, 2019 16:25
-
-
Save worldmind/14e2981814f1fa3e28a08a764cca9df9 to your computer and use it in GitHub Desktop.
Multiprocessing graceful stop by SIGTERM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from time import sleep | |
import signal | |
import multiprocessing as mp | |
_SIGTERM = None | |
def sigterm_handler(signum, frame): | |
global _SIGTERM | |
_SIGTERM.set() | |
def func(sigterm): | |
print(f"Start job: {mp.current_process().name}") | |
while True: | |
sleep(3) | |
print('Hardworking!') | |
if sigterm.is_set(): | |
print('Will stop by signal') | |
break | |
print('End job') | |
if __name__ == '__main__': | |
signal.signal(signal.SIGTERM, sigterm_handler) | |
mp.set_start_method('spawn') | |
_SIGTERM = mp.Event() | |
processes = [mp.Process(target=func, args=(_SIGTERM,)) for x in range(2)] | |
[p.start() for p in processes] | |
[p.join() for p in processes] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment