2013-01-09 92 views
0

這是Python 2.7。我已經成功地嘗試了文檔代碼:Python多處理池未啓動作業

from multiprocessing import Pool 

def f(x): 
    return x*x 

if __name__ == '__main__': 
    pool = Pool(processes=4)    # start 4 worker processes 
    result = pool.apply_async(f, [10]) # evaluate "f(10)" asynchronously 
    print result.get(timeout=1)   # prints "100" unless your computer is *very* slow 
    print pool.map(f, range(10))   # prints "[0, 1, 4,..., 81]" 

然後我自己開發的一個很簡單的例子失敗:

import multiprocessing 

def run_test_n(n): 
    print 'inside test %d' % n 
    with open('test%d.log' % n, 'w') as f: 
     f.write('test %d ok\n' % n) 

def runtests(ntests, nprocs): 
    pool = multiprocessing.Pool(processes = nprocs) 
    print 'runnning %d tests' % ntests 
    print 'over %d procs' % nprocs 
    tasks = range(1, ntests + 1) 
    results = [pool.apply_async(run_test_n, t) for t in tasks] 
    for r in results: 
     r.wait() 

if __name__ == '__main__': 
    runtests(5,5) 

在這個例子中,沒有創建文件並沒有「內部測試...」字符串被打印。

就好像run_test_n從來沒有被調用(它實際上從來沒有)。爲什麼?

回答

1

你在錯誤results = [pool.apply_async(run_test_n, t) for t in tasks];正確的形式是results = [pool.apply_async(run_test_n, (t,)) for t in tasks]

+0

你說得對。爲什麼? –

+0

@ PauloJ.Matos pool.apply_async(function_name,argv =(arg1,arg2,...,))。第二個參數應該是一個元組,最後一個逗號不應該被忽略。如果你有錯誤的列表,將不會有警告和例外。 –

+0

你是對的,但我確實發現它需要在元組中最後一個逗號。 –