Python Multi-Threading Detects End of One Thread

Asked 2 years ago, Updated 2 years ago, 86 views

def th1():
    a = 0
    for i in range(10):
        a = a + 1
def th2():
    while True:
        print("Loading")

Assume that when there are two functions, the th1 and th2 functions are rotated together by multi-threading. At this time, is there a way to run the th2 function only while the th1 function is running, and then automatically terminate the th2 function when all the operations of the th1 function are completed?

python multithreading

2022-09-22 14:27

1 Answers

is_alive can check if the thread is still running.

import threading
import time


def th1():
    print('th1 started.')    
    time.sleep(3)
    print('\nth1 exiting.')


def th2(t):
    print('th2 started.')    
    while True:
        if not t.is_alive():
            break
        print('.', end='', flush=True)
        time.sleep(.3)
    print('\nth2 exiting.')


t1 = threading.Thread(target=th1)
t2 = threading.Thread(target=th2, args=(t1,))

t1.start()
t2.start()


2022-09-22 14:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.