运行多个功能,我有以下代码如何在同一时间
my_func1()
my_func2()
my_func3()
my_func4()
my_func5()
是否有可能在同一时间来计算功能的数据,而不是一个又一个?
运行多个功能,我有以下代码如何在同一时间
my_func1()
my_func2()
my_func3()
my_func4()
my_func5()
是否有可能在同一时间来计算功能的数据,而不是一个又一个?
可以使用多或线程在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
样品,你可以阅读更多关于它在这里:
import thread
thread.start_new_thread(my_func1,())
thread.start_new_thread(my_func2,())
thread.start_new_thread(my_func3,())
thread.start_new_thread(my_func4,())
thread.start_new_thread(my_func5,())
你可以跟帖像
在python 3上做这个工作吗? – PiccolMan
看看这个答案为一个深入的答案:http://stackoverflow.com/questions/6319268/what-happened-to-thread-start-new-thread-in-python-3 – Yurippenet
from multiprocessing import Process
from time import sleep
def f(name):
print 'hello', name
sleep(1)
考虑以上:
,如果你要这样做:
f('bob') #start
f('alice') #wait until bob's done
f('jack') #wait until alice is done
f('cake') #wait until jack is done
f('paul') #wait until cake is done
print 'done'
你最终会等待5秒钟,你看到done
之前但是,如果你使用多,你可以生成多个进程同时运行的功能。
Process(target=f, args=('bob',)).start() #start now
Process(target=f, args=('alice',)).start() #start now
Process(target=f, args=('jack',)).start() #start now
Process(target=f, args=('cake',)).start() #start now
Process(target=f, args=('paul',)).start() #start now
print 'done' #start now
我喜欢的方式是使用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())
这将同时运行my_func1
,my_func2
和my_func3
,将arg1
和arg2
传递给每一个。一旦它们可用,它将按顺序打印所有结果。
你绝对确信你需要这么做吗? – TigerhawkT3
https://docs.python.org/2/library/multiprocessing.html – MattDMo
在同一时间?可能不会,但是你可以对它进行多处理,所以人们不必等待另一个完成 – taesu