Chinaunix首页 | 论坛 | 博客
  • 博客访问: 230513
  • 博文数量: 57
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 557
  • 用 户 组: 普通用户
  • 注册时间: 2015-10-01 18:05
文章分类

全部博文(57)

文章存档

2017年(57)

我的朋友

分类: Python/Ruby

2017-12-08 16:13:41

概念
     进程是程序在计算机上的一次执行活动。当你运行一个程序,你就启动了一个进程。显然,程序是死的(静态的),进程是活的(动态的)。进程可以分为系统进程和用户进程。凡是用于完成操作系统的各种功能的进程就是系统进程,它们就是处于运行状态下的操作系统本身;用户进程就不必我多讲了吧,所有由你启动的进程都是用户进程。进程是操作系统进行资源分配的单位。
     它的思想简单介绍如下:在操作系统的管理下,所有正在运行的进程轮流使用CPU,每个进程允许占用CPU的时间非常短(比如10毫秒),这样用户根本感觉不出来CPU是在轮流为多个进程服务,就好象所有的进程都在不间断地运行一样。但实际上在任何一个时间内有且仅有一个进程占有CPU。 

多进程

     多进程和多线程的区别:
     多线程使用的是cpu的一个核,适合io密集型
     多进程使用的是cpu的多个核,适合运算密集型
组件
     Python提供了非常好用的多进程包,multiprocessing,我们在使用的时候,只需要导入该模块就可以了。


Multiprocessing支持子进程,通信,共享数据,执行不同形式的同步,提供了Process,Pipe, Lock等组件


实例如下:

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # Author :Alvin.xie
  4. # @Time :2017-12-08 15:54
  5. # @file :1.py


  6. import multiprocessing
  7. p = multiprocessing.cpu_count()
  8. m = multiprocessing.active_children()
  9. print (p)
  10. print (m)
执行结果:
4
[]

Process


   1. 创建一个Process对象
   p = multiprocessing.Process(target=worker_1, args=(2, ))
   target = 函数名字
    args  =  函数需要的参数,以tuple的形式传入
注意: 单个元素的tuple的表现形式

multprocessing用到的两个方法
    cpu_count()  统计cpu总数
    active_children()  获得所有子进程

   2. Process的常用方法
     is_alive()             判断进程是否存活
     run()    启动进程
     start()     启动进程,会自动调用run方法,这个常用
     join(timeout)    等待进程结束或者直到超时

3. Process的常用属性
name   进程名字
     pid  进程的pid
实例如下:

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # Author :Alvin.xie
  4. # @Time :2017-12-08 16:06
  5. # @file :2.py

  6. import multiprocessing
  7. import time


  8. def work(interval, method):
  9.     print("start work_" + method)
  10.     time.sleep(interval)
  11.     print("end work_" + method)


  12. if __name__ == "__main__":
  13.     p1 = multiprocessing.Process(target=work, args=(1, "1"))
  14.     p2 = multiprocessing.Process(target=work, args=(2, "2"))
  15.     p3 = multiprocessing.Process(target=work, args=(3, "3"))
  16.     p1.start()
  17.     p2.start()
  18.     p3.start()

  19.     print('The Computer has {0} '.format(multiprocessing.cpu_count()))
  20.     for p in multiprocessing.active_children():
  21.         print("The name of active child is: " + p.name + ", pid is: " + str(p.pid) + "is alive: " + str(p.is_alive()))
  22.     print("MAIN IS END!")
执行结果:
The Computer has 4 
The name of active child is: Process-1, pid is: 6100is alive: True
The name of active child is: Process-3, pid is: 2604is alive: True
The name of active child is: Process-2, pid is: 7868is alive: True
MAIN IS END!
start work_1
start work_2
start work_3
end work_1
end work_2
end work_3






























阅读(1487) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~