python - 终止长时间运行的 python 线程

标签 python multithreading

在 python 中终止意外长时间运行的线程的推荐方法是什么?我不能使用 SIGALRM,因为

Some care must be taken if both signals and threads are used in the same program. The fundamental thing to remember in using signals and threads simultaneously is: always perform signal() operations in the main thread of execution. Any thread can perform an alarm(), getsignal(), pause(), setitimer() or getitimer(); only the main thread can set a new signal handler, and the main thread will be the only one to receive signals (this is enforced by the Python signal module, even if the underlying thread implementation supports sending signals to individual threads). This means that signals can’t be used as a means of inter-thread communication.Use locks instead.

更新:我案例中的每个线程都阻塞了——它正在使用 urllib2 模块下载网页,有时在速度极慢的站点上操作会花费太多时间。这就是为什么我要终止这么慢的线程

最佳答案

由于突然终止处于阻塞调用中的线程是不可行的,因此如果可能的话,更好的方法是避免使用线程,转而使用其他不会遇到此类问题的多任务机制。

对于 OP 的特定情况(线程的工作是下载网页,并且一些线程由于行为不当的站点而永远阻塞),理想的解决方案是 twisted -- 因为它通常用于网络任务。在其他情况下,multiprocessing可能会更好。

更一般地说,当线程给出无法解决的问题时,我建议切换到其他多任务机制,而不是尝试采取英雄措施来尝试让线程执行任务,至少在 CPython 中,它们不适合。

关于python - 终止长时间运行的 python 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1226091/

相关文章:

python - 如何在python中解析带有国际单词的文件

javascript - Django 模板变量和 Javascript

multithreading - 从 QRunnable 发出信号或发布事件

c++ - wait_until 在主线程中的工作方式与主线程中的工作方式是否不同?由 小码哥发布于

java - 匿名线程类无法访问非静态实例变量

android - 运行一段时间后,SurfaceView破坏Surface

c - 为多线程 UDP 客户端执行 'close ()' 时套接字描述符未释放

python - 使用正则表达式向 python 句子中的单词列表添加引号

python - 在列表中的 pandas 列中查找关键字匹配项的数量

python - 在 SPSS 中转置