gpt4 book ai didi

python - 如何在Python中使用concurrent.futures

转载 作者:行者123 更新时间:2023-12-01 02:03:16 30 4
gpt4 key购买 nike

我正在努力让多线程在 Python 中工作。我有一个函数,我想根据一个参数在 5 个线程上执行。我还需要每个线程都相同的 2 个参数。这就是我所拥有的:

from concurrent.futures import ThreadPoolExecutor

def do_something_parallel(sameValue1, sameValue2, differentValue):
print(str(sameValue1)) #same everytime
print(str(sameValue2)) #same everytime
print(str(differentValue)) #different

main():

differentValues = ["1000ms", "100ms", "10ms", "20ms", "50ms"]

with ThreadPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(do_something_parallel, sameValue1, sameValue2, differentValue) for differentValue in differentValues]

但我不知道下一步该做什么

最佳答案

如果您不关心顺序,现在可以执行以下操作:

from concurrent.futures import as_completed

# The rest of your code here

for f in as_completed(futures):
# Do what you want with f.result(), for example:
print(f.result())

否则,如果您关心顺序,则使用 ThreadPoolExecutor.mapfunctools.partial 来填充始终相同的参数可能是有意义的:

from functools import partial

# The rest of your code...

with ThreadPoolExecutor(max_workers=5) as executor:
results = executor.map(
partial(do_something_parallel, sameValue1, sameValue2),
differentValues
))

关于python - 如何在Python中使用concurrent.futures,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49358473/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com