简体   繁体   English

当线程在 ThreadPoolExecutor() 中死亡时,我如何捕捉?

[英]How can I catch when a thread dies in ThreadPoolExecutor()?

I have some very simple python code that runs a bunch of inputs through various processes via ThreadPoolExecutor().我有一些非常简单的 python 代码,这些代码通过 ThreadPoolExecutor() 通过各种进程运行一堆输入。 Now, sometimes one or more of the threads dies quietly.现在,有时一个或多个线程会安静地死掉。 It is actually great that the rest of the threads continue on and the code completes, but I would like to put together some type of summary that tells me which, if any, of the threads have died.线程的 rest 继续运行并且代码完成实际上很棒,但我想汇总一些类型的摘要,告诉我哪些线程(如果有的话)已经死亡。

I've found several examples where folks want the whole thing to shut down, but haven't seen anything yet where the process continues on and the threads that have hit errors are just reported on after the fact.我发现了几个例子,人们希望整个事情都关闭,但还没有看到任何进程继续进行的地方,并且发生错误的线程只是在事后报告。

Any/all thoughts greatly appreciated!任何/所有想法都非常感谢!

Thanks!谢谢!

import concurrent.futures as cf

with cf.ThreadPoolExecutor() as executor:
     executor.map(process_a, process_a_inputs)
     executor.map(process_b, process_b_inputs)

Executor.map does not support gathering more than one exception. Executor.map不支持收集多个异常。 However, its code can easily be adapted to return the arguments on which a failure occurred.但是,它的代码可以很容易地调整为返回发生故障的 arguments。

def attempt(executor: 'Executor', fn: 'Callable', *iterables):
    """Attempt to ``map(fn, *iterables)`` and return the args that caused a failure"""
    future_args = [(self.submit(fn, *args), args) for args in zip(*iterables)]

    def failure_iterator():
        future_args.reverse()
        while future_args:
            future, args = future_args.pop()
            try:
                future.result()
            except BaseException:
                del future
                yield args
    return failure_iterator()

This can be used to concurrently "map" arguments to functions, and later retrieve any failures.这可用于同时将 arguments “映射”到函数,然后检索任何故障。

import concurrent.futures as cf

with cf.ThreadPoolExecutor() as executor:
     a_failures = attempt(executor, process_a, process_a_inputs)
     b_failures = attempt(executor, process_b, process_b_inputs)
     for args in a_tries:
         print(f'failed to map {args} onto a')
     for args in b_tries:
         print(f'failed to map {args} onto b')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM