如何在 Python 中使用 concurrent.futures

编程入门 行业动态 更新时间:2024-10-17 07:28:42
本文介绍了如何在 Python 中使用 concurrent.futures的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

Im struggling to get multithreading working in Python. I have i function which i want to execute on 5 threads based on a parameter. I also needs 2 parameters that are the same for every thread. This is what i have:

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]

但我不知道接下来要做什么

But i don't know what to do next

推荐答案

如果你不关心顺序,现在可以这样做:

If you don't care about the order, you can now do:

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.map 和 functools.partial 来填充始终相同的参数可能是有意义的:

Otherwise, if you care about order, it might make sense to use ThreadPoolExecutor.map with functools.partial to fill in the arguments that are always the same:

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 中使用 concurrent.futures

本文发布于:2023-11-25 15:17:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630263.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Python   futures   concurrent

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!