進程池用法

#coding=utf-8

from multiprocessing import Pool
import os, time, random

def run_task(name):
    print 'Task %s (pid = %s) is running...' % (name, os.getpid())
    time.sleep(random.random() * 5)
    print 'Task %s end.' % name


if __name__ == '__main__':
    print 'Current process %s.' % os.getpid()
    p = Pool(processes =  3)
    for i in range(10):
        p.apply_async(run_task, i)

    print 'Waiting for all subprocesses done...'
    p.close()
    p.join()
    print "All subprocesses done."

#join()方法會等待全部的進程執行完畢, 調用join()以前必須先調用close()
#調用close()以後,進程池便沒法再添加新的進程
相關文章
相關標籤/搜索