Python:在线程中使用 ThreadPoolExecutor

问题描述 投票:0回答:1

我正在使用以下脚本在线程中使用 ThreadPoolExecutor:

def worker(x):
    return x*x


def FncWithinThread():
    with ThreadPoolExecutor(10) as executor:
        futures_t

在此输入

o_data = {executor.submit(worker, i):i for i in range(10)}

当您运行 FncWithinThread 函数时,它显示以下错误:

futures_to_data = {executor.submit(worker, i):i for i in range(10)}
                    ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\jhona\anaconda3\envs\Sandwich\Lib\concurrent\futures\thread.py", line 169, in submit
    raise RuntimeError('cannot schedule new futures after '
RuntimeError: cannot schedule new futures after interpreter shutdown

我尝试使用其他库,但使用 Requests.post 时,与 ThreadPoolExecutor 相比非常慢

python concurrency python-multithreading
1个回答
0
投票

看起来

ThreadPoolExecutor
正在线程内关闭。您应该确保
ThreadPoolExecutor
得到妥善管理并且不会过早关闭。这是一个例子:

from concurrent.futures import ThreadPoolExecutor

def worker(x):
    return x * x

def FncWithinThread():
    with ThreadPoolExecutor(10) as executor:
        # Create a list of futures
        futures = [executor.submit(worker, i) for i in range(10)]

    # You can now access the results if needed
    results = [future.result() for future in futures]

if __name__ == "__main__":
    FncWithinThread()
© www.soinside.com 2019 - 2024. All rights reserved.