2015-09-04 62 views
1

运行多个功能,我有以下代码如何在同一时间

my_func1() 
my_func2() 
my_func3() 
my_func4() 
my_func5() 

是否有可能在同一时间来计算功能的数据,而不是一个又一个?

+0

你绝对确信你需要这么做吗? – TigerhawkT3

+2

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

+0

在同一时间?可能不会,但是你可以对它进行多处理,所以人们不必等待另一个完成 – taesu

回答

1

可以使用多或线程在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 

样品,你可以阅读更多关于它在这里:

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

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

+0

这绝对计算我的数据a很快,但由于某些原因,我无法在计算时显示数据,如果您知道我的意思。 – PiccolMan

+0

我认为我的显示功能在多进程完成之前调用自己。在多进程功能完成后有没有办法调用我的显示功能? – PiccolMan

+0

是的,如果在所有进程中调用p.join()之后调用它。加入意味着它会等待,直到它完成,所以你可以等待,直到他们都完成了,而不仅仅是调用你的显示功能 – DorElias

2
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,()) 

你可以跟帖像

+0

在python 3上做这个工作吗? – PiccolMan

+0

看看这个答案为一个深入的答案:http://stackoverflow.com/questions/6319268/what-happened-to-thread-start-new-thread-in-python-3 – Yurippenet

0
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 
1

我喜欢的方式是使用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_func1my_func2my_func3,将arg1arg2传递给每一个。一旦它们可用,它将按顺序打印所有结果。