Python線程同步
主線程與子線程生命週期同步
1 默認情況下就是setDaemon(False),主線程執行完自己的任務以後退出,此時子線程會繼續執行自己的任務,直到自己的任務結束。
import threading
import time
def thread():
time.sleep(2)
print('---子線程結束---')
def main():
t1 = threading.Thread(target=thread)
t1.start()
print('---主線程--結束')
if __name__ =='__main__':
main()
2 當我們使用setDaemon(True)時,這是子線程爲守護線程,主線程一旦執行結束,則全部子線程被強制終止
import threading
import time
def thread():
time.sleep(2)
print('---子線程結束---')
def main():
t1 = threading.Thread(target=thread)
# 設置子線程守護主線程,主線程代碼全部執行完畢,子線程也會跟隨強制結束,主死 子死
t1.setDaemon(True)
t1.start()
# time.sleep(3)
print('---主線程結束---')
if __name__ =='__main__':
main()
3 timeout=n
import threading
import time
def thread():
time.sleep(2)
print('---子線程結束---')
def main():
for _ in range(5):
t1 = threading.Thread(target=thread)
t1.setDaemon(True) # 設置子線程爲守護線程
t1.start()
# time.sleep(2)
t1.join(timeout=2)
#1 不設timeout 主線程阻塞當前位置,子線程結束後再繼續執行後續代碼
#2 如果設置了setDaemon=True和timeout=1,主線程等待1s後會強制殺死子線程,然後主線程結束
#3 如果子線程執行時間少於timeout時間,那麼子線程結束後主線程便直接往下執行,無需等待timeout時間終止
print('---主線程結束---')
if __name__=='__main__':
main()
隨筆記之,如有問題,請留言。