Python how to create an automatically terminating child thread if the parent thread is not alive

How to create a python program that will generate multiple child threads. the main thread and the child thread are executed in parallel. the child thread should be checked periodically, if the parent is alive or not, if not alive, the entire child process should be completed.

+4
source share
2 answers

You can pass the link given threading.currentThread()from the parent to the child stream and periodically check if the parent is alive.

import threading
import time


class Child(threading.Thread):
    def __init__(self, parent_thread):
        threading.Thread.__init__(self)
        #self.daemon = True
        self.parent_thread = parent_thread

    def run(self):
        while self.parent_thread.is_alive():
            print "parent alive"
            time.sleep(.1)
        print "quiting"

Child(threading.currentThread()).start()
time.sleep(2)

As a second alternative, you can call self.parent_thread.join()to wait for a lock to complete this thread.

https://docs.python.org/2/library/threading.html#threading.Thread.join

daemon, , . , .

https://docs.python.org/2/library/threading.html#threading.Thread.daemon

+2

daemon Thread, :

import threading
import time

def worker():
    while True:
        time.sleep(1)
        print('doing work')

t = threading.Thread(target=worker)
t.daemon = True
t.start()

EDIT: :

my_threads = []
for i in range(0, 5):
    my_threads.append(threading.Thread(target=worker))
    my_threads[-1].daemon = True
0

Source: https://habr.com/ru/post/1607409/


All Articles