python 多进程multiprocessing 模块

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

猜你喜欢

转载自www.cnblogs.com/ExMan/p/9777890.html