国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python線程join方法原理解析

2020-02-15 21:16:36
字體:
供稿:網(wǎng)友

這篇文章主要介紹了python線程join方法原理解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

幾個事實

1 python 默認參數(shù)創(chuàng)建線程后,不管主線程是否執(zhí)行完畢,都會等待子線程執(zhí)行完畢才一起退出,有無join結(jié)果一樣

2 如果創(chuàng)建線程,并且設置了daemon為true,即thread.setDaemon(True), 則主線程執(zhí)行完畢后自動退出,不會等待子線程的執(zhí)行結(jié)果。而且隨著主線程退出,子線程也消亡。

3 join方法的作用是阻塞,等待子線程結(jié)束,join方法有一個參數(shù)是timeout,即如果主線程等待timeout,子線程還沒有結(jié)束,則主線程強制結(jié)束子線程。

4 如果線程daemon屬性為False, 則join里的timeout參數(shù)無效。主線程會一直等待子線程結(jié)束。

5 如果線程daemon屬性為True, 則join里的timeout參數(shù)是有效的, 主線程會等待timeout時間后,結(jié)束子線程。此處有一個坑,即如果同時有N個子線程join(timeout),那么實際上主線程會等待的超時時間最長為 N * timeout, 因為每個子線程的超時開始時刻是上一個子線程超時結(jié)束的時刻。

測試代碼

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),則根據(jù)timeout的不同,結(jié)果會不同,前提是設置了setDaemon(True),否則join的timeout是沒效的#設置了setDaemon(True),但是沒設置t.join()的運行結(jié)果:#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)的運行結(jié)果:#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)的運行結(jié)果,不過因為setDaemon的參數(shù)不是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(),沒有超時時間的阻塞的運行結(jié)果:#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()的運行結(jié)果:#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            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 九台市| 金溪县| 怀集县| 攀枝花市| 叙永县| 沂源县| 丰县| 庄浪县| 凌源市| 新昌县| 荥阳市| 徐闻县| 宁强县| 苏州市| 普兰店市| 贵阳市| 祥云县| 荃湾区| 临西县| 寻乌县| 铁岭县| 盘山县| 安泽县| 蓬溪县| 漯河市| 九龙城区| 南陵县| 高安市| 滦南县| 保山市| 北票市| 陆良县| 鄯善县| 鄂托克前旗| 视频| 磐安县| 两当县| 门头沟区| 九龙城区| 遵化市| 内江市|