python - 使用 ThreadingMixin 停止由 BaseHTTPServer 生成的线程

标签 python multithreading python-2.7 basehttpserver

我已在 this post 上阅读此处使用 ThreadingMixin(来自 SocketServer 模块),您可以使用 BaseHTTPServer 创建线程服务器。我试过了,它确实有效。但是,如何停止服务器生成的事件线程(例如,在服务器关闭期间)?这可能吗?

最佳答案

最简单的解决方案是只使用daemon_threads。简短的版本是:只需将其设置为 True,不要担心;当您退出时,任何仍在工作的线程都会自动停止。

作为ThreadingMixIn docs说:

When inheriting from ThreadingMixIn for threaded connection behavior, you should explicitly declare how you want your threads to behave on an abrupt shutdown. The ThreadingMixIn class defines an attribute daemon_threads, which indicates whether or not the server should wait for thread termination. You should set the flag explicitly if you would like threads to behave autonomously; the default is False, meaning that Python will not exit until all threads created by ThreadingMixIn have exited.

有关更多详细信息,请参阅 threading docs :

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property.

有时这是不合适的,因为您想在不退出的情况下关闭,或者因为您的处理程序可能需要完成清理工作。但当它合适时,您再简单不过了。

如果您只需要一种不退出即可关闭的方法,并且不需要保证清理,您可以通过 ctypeswin32api 使用特定于平台的线程取消 API 。这通常是个坏主意,但有时这正是您想要的。

如果您需要干净关闭,您需要为此构建自己的机器,让线程协作。例如,您可以创建一个受 threading.Condition 保护的全局“退出标志”变量,并让您的 handle 函数定期检查它。

如果线程只是在做缓慢的、非阻塞的工作,你可以把它分解成更小的部分,这就很好了。例如,如果 handle 函数始终至少每 5 秒检查一次退出标志,则可以保证能够在 5 秒内关闭线程。但是,如果线程正在执行阻塞工作怎么办——它们可能是这样,因为您使用 ThreadingMixIn 的全部原因是让您进行阻塞调用,而不是编写 select 循环或使用asyncore 之类的?

嗯,没有好的答案。显然,如果您只需要关闭“最终”而不是“在 5 秒内”发生(或者如果您愿意在 5 秒后放弃干净关闭,并恢复使用特定于平台的 API 或守护线程),您可以在每次阻塞调用之前和之后进行检查,它会“经常”起作用。但如果这还不够好,您真的无能为力。

如果您需要这样做,最好的办法是更改您的架构以使用能够执行此操作的框架。最受欢迎的选择是 Twisted , Tornado , 和 gevent .以后,PEP 3156将把类似的功能带入标准库,并且有一个部分完整的引用实现 tulip如果您不想为现实世界构建必须尽快准备好的东西,那值得一试。

关于python - 使用 ThreadingMixin 停止由 BaseHTTPServer 生成的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14284936/

相关文章:

java - 我不明白线程在这种情况下是如何工作的

python - 为什么 `int.__eq__(other)` 是工作比较?

python - 事务管理错误 :This is forbidden when an 'atomic' block is active while running unit test cases

Python 到 SQL 的连接。尝试将 pandas 数据框推送到 SQL Server

python - 无法解码任何 JSON

python - 在python中为RGB图像添加噪声

java - 我应该在虚拟机中使用多少个线程?

c++ - 如何快速发送大量 POST 请求

python-2.7 - 编程错误: can't adapt type 'hr.employee' in odoo10

python - 为什么 os.fdopen() 忽略 "mode"参数?