The role of join is highlighted. The work done by join is thread synchronization. That is, after the main thread task ends, it enters the blocking state and waits for the completion of other child threads before the main thread terminates.
join has a timeout parameter: (Recommended learning: Python video tutorial)
When setting up the guard When threading, it means that the main thread will kill the child thread while waiting for timeout, and finally exit the program. So, if there are 10 sub-threads, the total waiting time is the cumulative sum of each timeout. To put it simply, it is to give each sub-thread a timeout and let it execute it. When the time is up, it will be killed directly regardless of whether the task is completed or not.
When the daemon thread is not set, the main thread will wait for the accumulation of timeout and such a period of time. When the time is up, the main thread ends, but the child thread is not killed. The child thread can still continue to execute until All child threads end and the program exits.
The role of join
import threading import time def run(): time.sleep(2) print('当前线程的名字是: ', threading.current_thread().name) time.sleep(2) if __name__ == '__main__': start_time = time.time() print('这是主线程:', threading.current_thread().name) thread_list = [] for i in range(5): t = threading.Thread(target=run) thread_list.append(t) for t in thread_list: t.setDaemon(True) t.start() for t in thread_list: t.join() print('主线程结束了!' , threading.current_thread().name) print('一共用时:', time.time()-start_time)
For more Python-related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of How to use thread join in python. For more information, please follow other related articles on the PHP Chinese website!