Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Python多进程中使用pool

Python 多进程中使用pool,pool中指定每次运行几个进程,当其中一个进程结束完毕后,会加入新的进程#!/usr/bin/env python
#coding: utf-8
import multiprocessing
import os,time,randomdef Lee():
    print "Run task Lee-%s" %(os.getpid()) #os.getpid()获取当前的进程的ID
    start=time.time()
    time.sleep(random.random()*10) #random.random()随机生成0-1之间的小数
    end=time.time()
    print "Task Lee, runs %0.2f seconds." %(end - start)def Marlon():
    print "Run task Marlon-%s" %(os.getpid())
    start=time.time()
    time.sleep(random.random()*40)
    end=time.time()
    print "Task Marlon runs %0.2f seconds." %(end - start)def Allen():
    print "Run task Allen-%s" %(os.getpid())
    start=time.time()
    time.sleep(random.random()*30)
    end=time.time()
    print "Task Allen runs %0.2f seconds." %(end - start)def Frank():
    print "Run task Frank-%s" %(os.getpid())
    start=time.time()
    time.sleep(random.random()*20)
    end=time.time()
    print "Task Frank runs %0.2f seconds." %(end - start)
       
if __name__=="__main__":
    function_list=  [Lee,Marlon,Allen,Frank]
    print "parent process %s" %(os.getpid())
    pool=multiprocessing.Pool(2)
    for func in function_list:
        pool.apply_async(func) #Pool执行函数,apply执行函数,当有一个进程执行完毕后,会添加一个新的进程到pool中
    print "Waiting for all subprocesses done..."
    pool.close()
    pool.join() #调用join之前,一定要先调用close() 函数,否则会出错, close()执行后不会有新的进程加入到pool,join函数等待素有子进程结束
    print "All subprocesses done."--------------------------------------分割线 --------------------------------------CentOS上源码安装Python3.4  http://www.linuxidc.com/Linux/2015-01/111870.htm《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htmPython脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm在Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htmPython 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htmPython 的详细介绍:请点这里
Python 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-02/113562.htm