Python多处理池不启动作业

时间:2013-01-09 09:00:06

标签: python multiprocessing

这是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)

在此示例中,不会创建任何文件,也不会打印“内部测试...”字符串。

就好像从未调用run_test_n(实际上从未调用过)。为什么呢?

1 个答案:

答案 0 :(得分: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]