手机版
你好,游客 登录 注册
背景:
阅读新闻

Python多进程中使用pool

[日期:2015-02-16] 来源:Linux社区  作者:kobeyan [字体: ]

Python 多进程中使用pool,pool中指定每次运行几个进程,当其中一个进程结束完毕后,会加入新的进程

#!/usr/bin/env python
#coding: utf-8
import multiprocessing
import os,time,random

def 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.htm

Python脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的详细介绍请点这里
Python 的下载地址请点这里

本文永久更新链接地址http://www.linuxidc.com/Linux/2015-02/113562.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款