Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何停止ThreadPoolExecutor.map并在CTRL-C上退出?_Python 3.x_Python Multithreading - Fatal编程技术网

Python 3.x 如何停止ThreadPoolExecutor.map并在CTRL-C上退出?

Python 3.x 如何停止ThreadPoolExecutor.map并在CTRL-C上退出?,python-3.x,python-multithreading,Python 3.x,Python Multithreading,python脚本多次执行IO绑定函数(数量级:介于5000和75000之间)。通过使用 def _iterator(): ... # yields 5000-75000 different names def _thread_function(name): ... with concurrent.futures.ThreadPoolExecutor(max_workers=11) as executor: executor.map(_thread_function, _iterato

python脚本多次执行IO绑定函数(数量级:介于5000和75000之间)。通过使用

def _iterator(): ...  # yields 5000-75000 different names
def _thread_function(name): ...

with concurrent.futures.ThreadPoolExecutor(max_workers=11) as executor:
    executor.map(_thread_function, _iterator(), timeout=44)
如果用户按CTRL-C,它只会弄乱一个线程。我希望它停止启动新线程;完成当前正在进行的线程,或者立即杀死它们,不管怎样

我该怎么做呢?

也许能回答你的问题

本质上,从

如果func调用引发异常,则从迭代器检索其值时将引发该异常

由于您从未从map()检索值,因此在主线程中从未引发异常

此外,从

如果未处理的异常(包括但不限于StopIteration)由生成器函数引发或通过生成器函数传递,则该异常将以通常的方式传递给调用方,随后尝试恢复生成器函数将引发StopIteration。换句话说,未经处理的异常终止生成器的使用寿命

因此,如果将代码更改为(请注意
for
循环):

def_迭代器():…#产生5000-75000个不同的名称
定义线程函数(名称):。。。
以concurrent.futures.ThreadPoolExecutor(max_workers=11)作为执行器:
对于executor.map(_thread_函数,_iterator(),timeout=44)中的u):
通过

interruptederError
将在主线程中引发,通过传递生成器(
executor.map(\u thread\u函数,\u iterator(),timeout=44)
)它将终止它。

当我做那个简单的更改时,我会在一段时间后被TimeoutError击中。我不明白这会如何影响计时。从好的方面来说,我现在可以捕获一个异常,并调用executor.shutdown。处理异常需要一段时间,这很烦人,因为我无法立即向用户提供反馈:打印语句需要约20秒才能显示。这样,脚本在大约一分钟后退出,这无疑是一个巨大的改进。如果时间没有发生如此剧烈的变化就好了。这可能是因为之前仍然引发了异常,但您从未在主线程中收到它,因为该作业的结果从未从迭代器中检索到(请参阅地图文档的引用)。