Python concurrent.futures调用同一函数两次



如果我的所有进程都是从不同的函数启动的,那么我使用concurrent.futures没有问题。但是,如果我想用不同的参数调用同一个函数,我似乎无法获得正确的语法。这是我到目前为止得到的,但它不起作用:

tasks = ((serial_port_local, serial_options_local, serial_port_remote, serial_options_remote, "local"),
(serial_port_remote, serial_options_remote, serial_port_local, serial_options_local, "remote"))
for task in zip(tasks, executor.map(serial_cross_over, tasks)):
    print (task)

这是错误,但我不明白:

TypeError: serial_cross_over() missing 4 required positional arguments: 'receive_serial_options', 'send_serial_port', 'send_serial_options', and 'source'

事实上,我一点也不明白为什么它很复杂。难道我不应该做:

executor.submit(some_function(parameter1))
executor.submit(some_function(parameter2))

但这行不通。程序在第二次提交时挂起。为什么?

似乎serial_cross_over需要4个参数(如果我错了,请纠正我),而在.map时您没有提供它们,所以,也许可以看看这个答案:将多个参数传递给concurrent.futures.Executor.map?

tasks = ((serial_port_local, serial_options_local, serial_port_remote, serial_options_remote, "local"), (serial_port_remote, serial_options_remote, serial_port_local, serial_options_local, "remote"))
for task in zip(executor.map(lambda p: f(*p), tasks)):
    pass

至于为什么executor.submit没有按预期工作,我无法在没有更多细节的情况下说出。你试过这样吗?:

with ThreadPoolExecutor(max_workers=1) as executor:
    future = executor.submit(some_function, parameter1)
    print(future.result())

相关内容

  • 没有找到相关文章

最新更新