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