這篇文章主要介紹了python線程join方法原理解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
幾個事實
1 python 默認參數創建線程后,不管主線程是否執行完畢,都會等待子線程執行完畢才一起退出,有無join結果一樣
2 如果創建線程,并且設置了daemon為true,即thread.setDaemon(True), 則主線程執行完畢后自動退出,不會等待子線程的執行結果。而且隨著主線程退出,子線程也消亡。
3 join方法的作用是阻塞,等待子線程結束,join方法有一個參數是timeout,即如果主線程等待timeout,子線程還沒有結束,則主線程強制結束子線程。
4 如果線程daemon屬性為False, 則join里的timeout參數無效。主線程會一直等待子線程結束。
5 如果線程daemon屬性為True, 則join里的timeout參數是有效的, 主線程會等待timeout時間后,結束子線程。此處有一個坑,即如果同時有N個子線程join(timeout),那么實際上主線程會等待的超時時間最長為 N * timeout, 因為每個子線程的超時開始時刻是上一個子線程超時結束的時刻。
測試代碼
import threading,timedef func(): print "start thread time: ",time.strftime('%H:%M:%S') time.sleep(3) print "stop thread time: ",time.strftime('%H:%M:%S')thread_list = []for i in range(3): t1 = threading.Thread(target=func) #t1.setDaemon(True) thread_list.append(t1)for r in thread_list: r.start()for t in thread_list: #t.join(1) t.join()print "stop main thread"###子線程如果設置了t.join(timeout),則根據timeout的不同,結果會不同,前提是設置了setDaemon(True),否則join的timeout是沒效的#設置了setDaemon(True),但是沒設置t.join()的運行結果:#start thread time: 17:25:29#start thread time: 17:25:29#start thread time: 17:25:29#stop main thread#加了t1.setDaemon(True),并且設置了超時時間t.join(1)的運行結果:#start thread time: 17:12:24#start thread time: 17:12:24#start thread time: 17:12:24#stop main thread#沒加t1.setDaemon(True),并且設置了超時時間t.join(1)的運行結果,不過因為setDaemon的參數不是True所以就算設置了超時時間也沒用:#start thread time: 17:13:28#start thread time: 17:13:28#start thread time: 17:13:28#stop main thread#stop thread time: 17:13:31#stop thread time: 17:13:31#stop thread time: 17:13:31#沒加t1.setDaemon(True),但是設置了t.join(),沒有超時時間的阻塞的運行結果:#start thread time: 17:16:12#start thread time: 17:16:12#start thread time: 17:16:12#stop thread time: 17:16:15#stop thread time: 17:16:15#stop thread time: 17:16:15#stop main thread #即沒有設置setDaemon(True),也沒有設置join()的運行結果:#start thread time: 17:22:25#start thread time: 17:22:25#start thread time: 17:22:25#stop main thread#stop thread time: 17:22:28#stop thread time: 17:22:28#stop thread time: 17:22:28
新聞熱點
疑難解答