日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python线程join

發布時間:2025/3/20 python 14 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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, 因為每個子線程的超時開始時刻是上一個子線程超時結束的時刻。

測試代碼

''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助, 群里還有不錯的視頻學習教程和PDF電子書! ''' 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

總結:

如果想讓子進程正常的運行結束(子進程中所有的內容都運行了),則如果設置join(timeout)的話,前提是設置setDaemon(True),且setDaemon的參數為True,且join(timeout)的超時時間必須大于子進程執行所需的時間,不然沒等子進程運行結束就超時退出了.或者直接設置join()不帶超時時間,也不用設置setDaemon(True)了

總結

以上是生活随笔為你收集整理的python线程join的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。