首页 > 编程语言 > 详细

python 多进程multiprocessing 模块

时间:2017-12-18 13:23:27      阅读:220      评论:0      收藏:0      [点我收藏+]

multiprocessing 常用方法:

  • cpu_count():统计cpu核数

    multiprocessing.cpu_count()

  • active_children() 获取所有子进程

    multiprocessing.active_children()

  • preces() 创建一个进程对象

    multiprocessing.Preces(target=function_name, args=())

    target: 函数名
    
    args: 函数需要的参数,以tuple形式传入,一个参数时需(1,)

Preces 常用方法:

  • is_alive() 判断进程是否存在

  • run() 启动进程

  • start() 启动进程,会自动调用run方法,这个常用

  • join([timeout]) 等待进程结束或者直到超时
    • join() 方法说明:
    def def worker(interval):
        time.sleep(interval)
        print(‘hello world‘)
    P = multiprocessing.Process(target=worker, args=(5,))
    #-----------------------------------
    P.start()
    #设置timeout 设置超时时间
    print(P.is_alive())
    P.join(timeout=3)
    print(‘end main‘)
    ###
        True
        end main
        hello world
    #-----------------------------------
    P.start()
    P.alive()
    # 不调置timeout 超时时间
    P.join()
    print()
    ###
        True
        hello world
        end main
    #-----------------------------------
    结论:
    当join()不设置timeout时程序会一直等待上面的进程执行完成后再执行join()后面的代码
    当设置timeout时,无论上面的进程是否执行完成,程序运行到指定时间后就会执行后面的代码
    

    Preces 常用属性

  • namd 进程名子

  • pid 进程的pid

python 多进程multiprocessing 模块

原文:http://www.cnblogs.com/lijunjiang2015/p/8056971.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!