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

歡迎訪問 生活随笔!

生活随笔

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

python

python开两个守护线程_python 守护线程

發布時間:2024/9/27 python 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python开两个守护线程_python 守护线程 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

守護線程

如果python線程是守護線程,那么以為著這個線程是“不重要”的,“不重要”意味著如果他的父進程結束了但該守護線程沒有運行完,守護進程就會被強制結束。如果線程是非守護線程,那么父進程只有等到守護線程運行完畢后才能結束。

在python中,線程通過threadName.setDaemon(True|False)來設置是否為守護線程

代碼實例

父進程中調用兩個線程,但父進程會瞬間運行完,觀察兩個線程的運行情況。

import time import threadingdef write(content):start_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))string = "start writting %s at %s" % (content, start_time)print(string)time.sleep(5)end_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))string = "start writting %s at %s" % (content, end_time)print(string)def watch(content):start_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))string = "start watching %s at %s" % (content, start_time)print(string)time.sleep(5)end_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))string = "start watching %s at %s" % (content, end_time)print(string)threads = [] t1 = threading.Thread(target=write, args=("poem",)) t2 = threading.Thread(target=watch, args=("video",)) threads.append(t1) threads.append(t2)def for_test():for thread in threads:thread.setDaemon(False)thread.start()print("main over")if __name__ == '__main__':for_test()

運行結果:

可以看到主線程瞬間結束,但是等待到子線程均運行完畢之后程序才退出。

import time import threadingdef write(content):start_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))string = "start writting %s at %s" % (content, start_time)print(string)time.sleep(5)end_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))string = "start writting %s at %s" % (content, end_time)print(string)def watch(content):start_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))string = "start watching %s at %s" % (content, start_time)print(string)time.sleep(5)end_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))string = "start watching %s at %s" % (content, end_time)print(string)threads = [] t1 = threading.Thread(target=write, args=("poem",)) t2 = threading.Thread(target=watch, args=("video",)) threads.append(t1) threads.append(t2)def for_test():for thread in threads:thread.setDaemon(True)thread.start()if __name__ == '__main__':print("main start a t %s" %(time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))))for_test()print("main end at %s" %(time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))))

運行結果:

我們可以看到主線程結束之后整個程序即退出了。

更新時間: 2019 11 12

總結

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

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