day36-多进程多线程一

多进程


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

多进程和多线程的区别:

多线程使用的是cpu的一个核,适合io密集型
多进程使用的是cpu的多个核,适合运算密集型

组件:

Python提供了非常好用的多进程包,multiprocessing,我们在使用的时候,只需要导入该模块就可以了。

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

Process

1. 创建一个Process对象
p = multiprocessing.Process(target=worker_1, args=(2, ))

target = 函数名字
args = 函数需要的参数,以tuple的形式传入
注意: 单个元素的tuple的表现形式


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

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

 Process的常用属性
name 进程名字
pid 进程的pid

例子:

import multiprocessing
import time
def work(interval, method):
    print("start work_" + method)
    time.sleep(interval)
    print("end work_" + method)


if __name__ == "__main__":
    p1 = multiprocessing.Process(target=work, args=(1, "1"))
    p2 = multiprocessing.Process(target=work, args=(2, "2"))
    p3 = multiprocessing.Process(target=work, args=(3, "3"))
    p1.start()
    p2.start()
    p3.start()
    print("The number of CPU is:") + str(multiprocessing.cpu_count())
    for p in multiprocessing.active_children():
    print("The name of active child is: " + p.name + ", pid is: " + str(p.pid) + "is alive: " + str(p.is_alive()))   print("MAIN IS END!")

结果
The number of CPU is:4
The name of active child is: Process-3, pid is9788is alive: True
The name of active child is: Process-1, pid is6936is alive: True
The name of active child is: Process-2, pid is3052is alive: True
MAIN IS END!
start work_2
start work_1
start work_3
end work_1
end work_2
end work_3
原文地址:https://www.cnblogs.com/wxp997/p/8012568.html