3 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超13個贊
你可以使用threading
或multiprocessing
。
由于CPython的特殊性,threading
不太可能實(shí)現(xiàn)真正的并行性。出于這個原因,multiprocessing
通常是一個更好的選擇。
這是一個完整的例子:
from multiprocessing import Processdef func1(): print 'func1: starting' for i in xrange(10000000): pass print 'func1: finishing'def func2(): print 'func2: starting' for i in xrange(10000000): pass print 'func2: finishing'if __name__ == '__main__': p1 = Process(target=func1) p1.start() p2 = Process(target=func2) p2.start() p1.join() p2.join()
啟動/加入子進(jìn)程的機(jī)制可以很容易地封裝到一個函數(shù)中runBothFunc
:
def runInParallel(*fns): proc = [] for fn in fns: p = Process(target=fn) p.start() proc.append(p) for p in proc: p.join()runInParallel(func1, func2)

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超5個贊
這可以通過Ray優(yōu)雅地完成,這個系統(tǒng)允許您輕松地并行化和分發(fā)Python代碼。
要并行化您的示例,您需要使用@ray.remote
裝飾器定義您的函數(shù),然后使用它來調(diào)用它們.remote
。
import ray ray.init()dir1 = 'C:\\folder1'dir2 = 'C:\\folder2'filename = 'test.txt'addFiles = [25, 5, 15, 35, 45, 25, 5, 15, 35, 45]# Define the functions. # You need to pass every global variable used by the function as an argument.# This is needed because each remote function runs in a different process,# and thus it does not have access to the global variables defined in # the current process.@ray.remotedef func1(filename, addFiles, dir): # func1() code here...@ray.remotedef func2(filename, addFiles, dir): # func2() code here...# Start two tasks in the background and wait for them to finish.ray.get([func1.remote(filename, addFiles, dir1), func2.remote(filename, addFiles, dir2)])
如果將相同的參數(shù)傳遞給兩個函數(shù)并且參數(shù)很大,則更有效的方法是使用ray.put()
。這避免了大型參數(shù)被序列化兩次并創(chuàng)建它的兩個內(nèi)存副本:
largeData_id = ray.put(largeData)ray.get([func1(largeData_id), func2(largeData_id)])
如果func1()
并func2()
返回結(jié)果,則需要重寫代碼,如下所示:
ret_id1 = func1.remote(filename, addFiles, dir1)ret_id2 = func1.remote(filename, addFiles, dir2)ret1, ret2 = ray.get([ret_id1, ret_id2])
在多處理模塊上使用Ray有許多優(yōu)點(diǎn)。特別是,相同的代碼將在一臺機(jī)器上運(yùn)行,也可以在一組機(jī)器上運(yùn)行。有關(guān)Ray的更多優(yōu)點(diǎn),請參閱此相關(guān)帖子。
添加回答
舉報