簡體   English   中英

Python Multiprocessing Pool無法啟動作業

[英]Python Multiprocessing Pool not launching jobs

這是Python 2.7。 我已經成功嘗試了文檔代碼:

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)

在此示例中,不創建任何文件,也不打印“ inside test ...”字符串。

好像從未調用過run_test_n(實際上從未調用過)。 為什么?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM