python子線程退出


 

def thread_func():
   
   while True:
           #do something
           #do something
           #do something
 
t=threading.Thread(target = thread_func)
t.start()

# main thread do something
# main thread do something
# main thread do something

跑起來是沒有問題的,但是使用ctrl + c中斷的時候出問題了,主線程退出了,但子線程仍然運行。

於是在主線程增加了信號處理的代碼,收到sigint時改變子線程循環條件

loop = True
def thread_func():
   
   while loop:
           #do something
           #do something
           #do something
 
t=threading.Thread(target = thread_func)
t.start()

# ctrl+c時,改變loop為False
def handler(signum, frame):
    global loop
    loop = False
    t.join()
    exit(0)
signal(SIGINT, handler)


# main thread do something
# main thread do something
# main thread do something

這樣ctrl+c就可以退出了,但是疑惑的是,主線程退出進程不會退出嗎?

 

這里有個參考,講線程deamon屬性,可能於此相關,需要抽時間學習:

https://blog.csdn.net/oh5W6HinUg43JvRhhB/article/details/89062363

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM