python 27进程池

来源:互联网 发布:淘宝网上三唑仑叫什么 编辑:程序博客网 时间:2024/05/18 03:22

Pool类可以提供指定数量的进程供用户调用,当有新的请求提交到Pool中时,如果池还没有满,就会创建一个新的进程来执行请求。如果池满,请求就会告知先等待,直到池中有进程结束,才会创建新的进程来执行这些请求。
下面介绍一下multiprocessing 模块下的Pool类下的几个方法

import multiprocessingdef do_calculation(data):    return data*2def start_process():    print 'Starting',multiprocessing.current_process().nameif __name__=='__main__':    inputs=list(range(10))    print 'Inputs  :',inputs    builtin_output=map(do_calculation,inputs)    print 'Build-In :', builtin_output    pool_size= 3    print pool_size    pool=multiprocessing.Pool(processes=pool_size,        initializer=start_process,)    pool_outputs=pool.map(do_calculation,inputs)    pool.close()    pool.join()    print 'Pool  :',pool_outputs
Inputs  : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]Build-In : [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]3Starting PoolWorker-257Starting PoolWorker-258Starting PoolWorker-259Pool  : [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
import multiprocessingimport timedef func(msg):    for i in xrange(3):        print msg        time.sleep(1)    return "done " + msgif __name__ == "__main__":    pool = multiprocessing.Pool(processes=4)    result = []    for i in xrange(4):        msg = "hello %d" %(i)        result.append(pool.apply_async(func, (msg, )))    pool.close()    pool.join()    for res in result:        print res.get()    print "Sub-process(es) done."
hello 0hello 2hello 1hello 3hello 0hello 2hello 1hello 3hello 0hello 1hello 2hello 3done hello 0done hello 1done hello 2done hello 3Sub-process(es) done.

这个也不错
http://blog.csdn.net/seetheworld518/article/details/49639651

0 0
原创粉丝点击