如果发生异常,立即停止并发作业

时间:2019-08-10 22:02:23

标签: python exception concurrent.futures

我正在使用python模块concurrent.futures向本地服务器发出〜1M个HTTP请求。 request_service函数如下所示

def request_service(url, value):
    """Make single HTTP request and raise exception if occurs."""

    try:
        response = requests.get(url + '/key=' + value)
    except Exception1:
        raise
    except Exception2:
        raise

我使用了15名工人来完成此并发任务,但是还想立即在任何请求失败并引发异常的情况下立即停止任务。

我将并发部分放在try-except块中,但似乎该作业从未引发任何异常,而是继续运行。

values = [value1, value2, ...]

with ThreadPoolExecutor(max_workers=15) as executor:
    try:
        for _ in executor.map(request_service, values):
            pass
    except:
        logging.exception('Error in request_service()')
        exit(1)

我想知道使用全局标志来指示是否发生异常,并在request_service函数的开始处添加测试。但是这种方法似乎不安全且效率低下。

如果发生异常,是否有更好的方法立即停止并发作业?感谢您的帮助。

0 个答案:

没有答案
相关问题