![](/img/trans.png)
[英]How to run N threads of the same functions with different parameters in parallel? - python
[英]Run same function in parallel with different parameters and know which parallel run has ended in python
我有一个执行函数,它应该在多个设备上并行运行。 我需要在完成每个并行运行时调用不同的函数。 我不能等待所有并行调用完成,因为根据传递的参数,它需要非常不同的时间。
def func1(device, arg1, arg2):
# do something
for device in devices:
# Call func1 with different arguments in parallel
# If one of the parallel is finished call func2(arg, arg1, arg2) with different arguments.
我怎样才能在 Python 中做到这一点?
请参阅此代码示例,它使用future.ThreadPoolExecutor
进行并行执行。
from concurrent.futures import ThreadPoolExecutor, Future, as_completed
devices = []
def func1(device, arg1, arg2):
pass
def do_after_func1(func1_result: Future):
identifier = func1_result.arg
result = func1_result.result()
# do what ever
pass
device_executors = ThreadPoolExecutor(max_workers=20)
args = [] # can be anything
futures = []
for device in devices:
tracker = device_executors.submit(func1, *args)
tracker.arg = "some-identififcation-if-you-need"
tracker.add_done_callback(do_after_func1)
futures.append(tracker)
您可以将任何要并行执行的内容作为callable
提交,结果可以do_after_func1
到回调函数do_after_func1
。 您可以在此处决定之后要调用的内容。 所有这些都是并行发生的。
如果您认为需要多个进程,也可以使用ProcessPoolExecutor
。
您可以从官方文档中了解更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.