python & db 异步请求(又名即发即弃):如何?

python & db async requests (aka fire-and-forget): how to?

在一个函数的中间,我希望能够触发对 DB 的调用(刻录结果),但该函数保持 运行,这样我就不会遇到 I/O瓶颈。这是 不是 网络应用程序。全部离线。

用于解释目的的代码段:

a = list(range(100))
for i in a:
    my_output = very_long_function(i)
    # I'd like to_sql to run in a "fire-and-forget fashion"
    function_of_choice_to_sql(my_output)

我想知道 threading 库、asyncio 或其他工具是否更好。我在 none 的这项特殊努力中没有成功。我会采取任何可行的解决方案。

有什么帮助吗?

p.s.: concurrency/locking 等不会有问题,因为在我的如果我的函数计算的时间远远大于写入数据库的时间。

您可以使用 ThreadPoolExecutor, it provides a simple interface to schedule callables to a pool of worker. In particular, you might be interested in the map 方法:

from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(max_workers=4) as executor:
    # Lazy map (python3 only)
    outputs = map(very_long_function, range(10)) 
    # Asynchronous map
    results = executor.map(function_of_choice_to_sql, outputs)
    # Wait for the results
    print(list(results))