python子线程退出

2022-10-14,,

 

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

 

《python子线程退出.doc》

下载本文的Word格式文档,以方便收藏与打印。