Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.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的资源_Python 3.x_Threadpool - Fatal编程技术网

Python 3.x 正在释放ThreadPoolExecutor的资源

Python 3.x 正在释放ThreadPoolExecutor的资源,python-3.x,threadpool,Python 3.x,Threadpool,我试图使用threadPoolExcecutor实现对API请求的异步处理,同时限制服务器上的线程数量。我的目标是在异步模式下处理繁重的请求,当API接收到请求时,调用方法submit\u request,它应该立即返回序列ID,并在后台执行繁重的数据处理,以便不会阻止后续调用。我将数据传递给一个线程函数,该函数通过executor.submit方法调用。我还需要通过指定max_workers来限制正在启动的线程的数量。下面的示例实现了这个目标;但是,通常使用上下文管理器调用执行器,以释放资源。

我试图使用threadPoolExcecutor实现对API请求的异步处理,同时限制服务器上的线程数量。我的目标是在异步模式下处理繁重的请求,当API接收到请求时,调用方法
submit\u request
,它应该立即返回序列ID,并在后台执行繁重的数据处理,以便不会阻止后续调用。我将数据传递给一个线程函数,该函数通过
executor.submit
方法调用。我还需要通过指定max_workers来限制正在启动的线程的数量。下面的示例实现了这个目标;但是,通常使用上下文管理器调用
执行器
,以释放资源。如果我将
关键字一起与executor一起使用,那么序列ID将不会立即返回,这与目的背道而驰。如果在要提交的调用行之后使用
b.result()
,那么对API的调用将再次变为阻塞和同步。我的问题是,就发布资源而言,这种调用已经足够好了,或者我需要
.result()
上下文管理器?当然,如何实现异步调用并安全地限制已启动线程的数量,而不会在不释放资源的情况下造成泄漏呢?谢谢

import concurrent.futures
def threadFunc(request):
    print("do some heavy work here!!")

class process_request():
    def __init__(self):
        self._current_sequence_id = 0
        self._executor = ThreadPoolExecutor(max_workers=2)

    def submit_request(self, data):
        self._current_sequence_id += 1
        print("Processing request")            
        b = self._executor.submit(threadFunc, data)
        return self._current_sequence_id

您不必清理未来,但在某个时刻(当没有更多工作要做时),执行器本身只需调用其
shutdown()
方法。此外,如果您的任务产生结果,那么您将希望将它们与序列ID关联。