首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在ThreadPoolExecutor (Python)中正确指定超时?

如何在ThreadPoolExecutor (Python)中正确指定超时?
EN

Stack Overflow用户
提问于 2021-01-27 15:39:37
回答 1查看 458关注 0票数 0

我有下面的代码,在这里我尝试用不同的超时调用函数。第一个函数可能超时,但第二个函数可能在指定的时间内执行。

代码语言:javascript
复制
import time
from concurrent.futures import ThreadPoolExecutor

def test1(a, b, c):
    time.sleep(5)
    d=a+b+c
    print(d)

def test2(a, b):
    time.sleep(5)
    d=a+b
    print(d)

with ThreadPoolExecutor(max_workers=1) as executor1:
    try:
        executor1.submit(test1, 1,2,3).result(timeout=1)
    except:
        executor1.shutdown(wait=False)
        print("Pass")

with ThreadPoolExecutor(max_workers=1) as executor2:
    try:
        executor2.submit(test2, 1,2).result(timeout=8)
    except:
        executor2.shutdown(wait=False)
        print("Pass-2")

预期输出

代码语言:javascript
复制
Pass
3

实际输出

代码语言:javascript
复制
Pass
6
3

我想要的是,只要有一个executor,就停止第一个timeout的执行。然后继续下一个executor

EN

回答 1

Stack Overflow用户

发布于 2021-01-27 16:00:42

最后,利用this link实现了该系统。最终代码共享如下:

代码语言:javascript
复制
import time
from concurrent.futures import ThreadPoolExecutor
import ctypes

def terminate_thread(thread):
    """Terminates a python thread from another thread.

    :param thread: a threading.Thread instance
    """
    if not thread.isAlive():
        return

    exc = ctypes.py_object(SystemExit)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
        ctypes.c_long(thread.ident), exc)
    if res == 0:
        raise ValueError("nonexistent thread id")
    elif res > 1:
        # """if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")

def test1(a, b, c):
    time.sleep(5)
    d=a+b+c
    print(d)

def test2(a, b):
    time.sleep(5)
    d=a+b
    print(d)

with ThreadPoolExecutor(max_workers=1) as executor:
    try:
        executor.submit(test1, 1,2,3).result(timeout=1)
    except:
        executor.shutdown(wait=False)
        for t in executor._threads:
            terminate_thread(t)
        print("Pass")

with ThreadPoolExecutor(max_workers=1) as executor:
    try:
        executor.submit(test2, 1,2).result(timeout=8)
    except:
        executor.shutdown(wait=False)
        for t in executor._threads:
            terminate_thread(t)
        print("Pass-2")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65922433

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档