How to stop the first thread when the second thread is completed in python?

Is there a way to stop the first thread when the second thread completes?

Example:

from functools import partial import threading def run_in_threads(*functions): threads=[] for function in functions: thread=threading.Thread(target=function) thread.start() threads.append(thread) for thread in threads: thread.join() def __print_infinite_loop(value): while True:print(value) def __print_my_value_n_times(value,n): for i in range(n):print(value) if __name__=="__main__": run_in_threads(partial(__print_infinite_loop,"xyz"),partial(__print_my_value_n_times,"123",1000)))))) 

In the above axample, I run two functions on threads, and I have to stop the first thread when the second is finished. I read that it supports events, but unfortunately I have not used it yet.

+4
source share
1 answer

You can use threading.Event as follows:

 import functools import threading def run_in_threads(*functions): threads = [] for function in functions: thread = threading.Thread(target = function) thread.daemon = True thread.start() threads.append(thread) for thread in threads: thread.join() def __print_infinite_loop(value, event): while not event.is_set(): print(value) def __print_my_value_n_times(value, n, event): for i in range(n): print(value) event.set() if __name__ == "__main__": event = threading.Event() infinite_loop = functools.partial(__print_infinite_loop, "xyz", event) my_values = functools.partial(__print_my_value_n_times, "123", 10, event) run_in_threads(infinite_loop, my_values) 
+1
source

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


All Articles