国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 囊谦县| 宽城| 珠海市| 长武县| 延寿县| 梨树县| 金寨县| 耿马| 错那县| 龙海市| 连南| 崇义县| 博爱县| 沧州市| 保靖县| 宁南县| 镇沅| 文安县| 宜阳县| 阳东县| 台北市| 汉沽区| 东阿县| 常宁市| 云梦县| 长春市| 司法| 阜新| 温州市| 祁连县| 宣恩县| 阜宁县| 沾化县| 南部县| 黑龙江省| 荆州市| 罗源县| 沙洋县| 九台市| 丹凤县| 昌吉市|