Python concurrent.futures两次调用相同的函数

时间:2016-07-31 03:56:01

标签: python concurrent-programming

如果我的所有进程都是从不同的函数启动的,那么使用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))

但这并不奏效。该程序挂起第二次提交。为什么呢?

1 个答案:

答案 0 :(得分:0)

似乎serial_cross_over需要4个参数(如果我错了,请更正我)并且当.map这样时你不提供它们, 也许看一下这个答案:Pass multiple parameters to 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

至于为什么没有执行者提交按预期工作,我不知道没有进一步的细节。你试过这样的吗?:

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