请问在python的多线程编程中,如何关闭一个线程?
来源:6-3 操作系统内存管理机制与Python垃圾回收面试题

慕仔9271372
2019-03-08
看了文档,只有join函数是等待线程结束,如何主动关闭线程呢?谢谢~
写回答
1回答
-
python 中并没有直接提供可以结束一个线程的方法,如果你留意文档有这么几句
Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.
一般有这么几种
- 守护线程。守护线程随着主线程结束退出
- 使用信号机制。threading.Event见 github 示例。
- 状态轮询。比如设置一个 running =True 的状态通过轮询该状态是否为 Flase 退出循环
参考
https://stackoverflow.com/questions/43683257/python-close-a-thread-on-multithreading
112019-03-13
相似问题