multithreading - Running Python multi-threaded process & interrupt a child thread with a signal -
i trying write python multi-threaded script following 2 things in different threads:
- parent: start child thread, simple task, stop child thread
- child: long running task.
below simple way it. , works me:
from multiprocessing import process import time def child_func(): while not stop_thread: time.sleep(1) if __name__ == '__main__': child_thread = process(target=child_func) stop_thread = false child_thread.start() time.sleep(3) stop_thread = true child_thread.join()
but complication arises because in actuality, instead of while-loop in child_func()
, need run single long-running process doesn't stop unless killed ctrl-c. cannot periodically check value of stop_thread
in there. how can tell child process end when want to?
i believe answer has using signals. haven't seen example of how use them in exact situation. can please modifying code above use signals communicate between child , parent thread. , making child-thread terminate iff user hits ctrl-c.
there no need use signal
module here unless want cleanup on child process. possible stop child processes using terminate
method (which has same effect sigterm
)
from multiprocessing import process import time def child_func(): time.sleep(1000) if __name__ == '__main__': event = event() child_thread = process(target=child_func) child_thread.start() time.sleep(3) child_thread.terminate() child_thread.join()
the docs here: https://docs.python.org/2/library/multiprocessing.html#multiprocessing.process.terminate
Comments
Post a Comment