Python ThreadPoolExecutor 终止所有线程

标签 python multithreading threadpoolexecutor concurrent.futures

我正在运行一段 python 代码,其中多个线程通过线程池执行程序运行。每个线程都应该执行一项任务(例如获取网页)。我想要做的是终止所有线程,即使其中一个线程失败。例如:

with ThreadPoolExecutor(self._num_threads) as executor:
    jobs = []
    for path in paths:
        kw = {"path": path}
        jobs.append(executor.submit(start,**kw))
    for job in futures.as_completed(jobs):
        result = job.result()
        print(result)
def start(*args,**kwargs):
    #fetch the page
    if(success):
        return True
    else:
        #Signal all threads to stop

有可能这样做吗?除非所有线程都成功,否则线程返回的结果对我来说毫无用处,因此即使其中一个失败,我想节省其余线程的一些执行时间并立即终止它们。实际的代码显然是在做相对冗长的任务,有几个失败点。

最佳答案

如果你已经完成了线程并想查看进程,那么这里的代码和平看起来非常有前途和简单,几乎与线程相同的语法,但使用多处理模块。
当超时标志到期时进程终止,非常方便。

import multiprocessing

def get_page(*args, **kwargs):
    # your web page downloading code goes here

def start_get_page(timeout, *args, **kwargs):
    p = multiprocessing.Process(target=get_page, args=args, kwargs=kwargs)
    p.start()
    p.join(timeout)
    if p.is_alive():
        # stop the downloading 'thread'
        p.terminate()
        # and then do any post-error processing here

if __name__ == "__main__":
    start_get_page(timeout, *args, **kwargs)

关于Python ThreadPoolExecutor 终止所有线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62474014/

相关文章:

python - Sqlite3游标实时更新?

python - 编写一个函数来使用 time_t 显示当前日期?

c# - C#更改另一个线程上的表单字符串

java - 清理 ThreadPoolExecutor 中的有界队列

java - tomcat:WAITING条件线程

python - 如何设置gunicorn脚本(django)

python - 如何在python中计算数组的绝对值?

C++ getline(string) 与多线程有关的段错误

linux - 多个线程定期更新全局变量,而第三个线程等待读取

java - ThreadPoolExecutor 中的核心线程是什么?