在函数的中间,我希望能够触发对DB的调用(刻录结果),但是函数继续运行,这样我就不会遇到I/O瓶颈。这是,而不是,一个web应用程序。一切都离线了。
用于解释性目的的片段:
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)我想知道使用线程库、异步或其他工具是否更好。在这一特别的努力中,我没有一次失败。我会采取任何有效的解决办法。
有什么帮助吗?
concurrency/locking和类似的东西不会有问题,因为在我的例子中,我的函数计算的时间远远大于写数据库的时间。
发布于 2017-02-16 09:36:30
您可以使用ThreadPoolExecutor,它提供了一个简单的接口来调度员工池的可调用性。特别是,您可能对地图方法感兴趣:
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))https://stackoverflow.com/questions/42269180
复制相似问题