Last active
July 26, 2024 14:59
-
-
Save mgax/642c816b774a3b2bae4dcfac2d7d0d8b to your computer and use it in GitHub Desktop.
Prototype of task loop that reliably kills runaway tasks
This file contains hidden or 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
import multiprocessing | |
import os | |
import signal | |
from itertools import count | |
from time import sleep | |
def work(n): | |
print("Task", n, "starting") | |
signal.signal(signal.SIGINT, signal.SIG_IGN) | |
while True: | |
try: | |
sleep(2) | |
except KeyboardInterrupt: | |
print("Task interrupted") | |
if os.environ.get("HIGHLANDER"): | |
print("Task does not want to die") | |
else: | |
print("Task done") | |
return | |
def start_task(n): | |
task = multiprocessing.Process(target=work, args=(n,)) | |
task.start() | |
return task | |
def task_loop(): | |
for n in count(): # or `while True:` | |
print("Loop starting task", n) | |
task = start_task(n) | |
try: | |
task.join() | |
print("Loop task", n, "finished") | |
except KeyboardInterrupt: | |
print("Loop waiting for task", n, "to finish ...") | |
try: | |
task.join() | |
finally: | |
if task.is_alive(): | |
print("Loop killing task", n) | |
task.kill() | |
return | |
if __name__ == "__main__": | |
task_loop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment