如何同时运行多个函数

Pic*_*Man 6 python

我有以下代码

my_func1()
my_func2()
my_func3()
my_func4()
my_func5()
Run Code Online (Sandbox Code Playgroud)

是否可以同时计算函数的数据,而不是一个接一个?

Gia*_*lli 11

我最喜欢的方法是使用concurrent.futures,它是一个标准的 Python 库(3.2 及以上版本或作为 Python 2.7 的单独包提供):

from concurrent.futures import ThreadPoolExecutor

executors_list = []

with ThreadPoolExecutor(max_workers=5) as executor:
    executors_list.append(executor.submit(my_func1, arg1, arg2))
    executors_list.append(executor.submit(my_func2, arg1, arg2))
    executors_list.append(executor.submit(my_func3, arg1, arg2))

for x in executors_list:
    print(x.result())
Run Code Online (Sandbox Code Playgroud)

这将同时运行my_func1,my_func2my_func3,将arg1和传递arg2给每个人。然后,一旦所有结果可用,它就会按顺序打印所有结果。


Dor*_*ias 6

您可以在 python 中使用多处理或线程线程实际上并不会并行运行,但允许您同时运行这些函数(并且 python 将迭代它们,一次执行几行)

使用多处理,它们将并行运行(假设您有多个 CPU 内核),但它们不会共享内存。这是一个多处理示例

from multiprocessing import Process
p = Process(target=myfunc1)
p.start()
p2 = Process(target=myfunc2)
p2.start()
# and so on
p.join()
p2.join()
# the join means wait untill it finished
Run Code Online (Sandbox Code Playgroud)

你可以在这里读更多关于它的内容:

https://docs.python.org/2/library/multiprocessing.html

https://wiki.python.org/moin/GlobalInterpreterLock