多进程的概念:
简单来说:当你在系统上开启一个程序那么你便开启了一个进程。启动为“进程”不启动那就是“程序”。
系统进程:凡是用来操作完成系统各种功能的就是系统进程。
用户进程:凡是由人启动的程序就是系统进程。
对于CPU:所有进程都是轮流占用CUP并且使用时间极短。任时间只有一个进程占用CPU。
多进程与多线程的区别:
多线程:使用CPU的一个核,适合IO密集型
多进程:使用CPU的所有核,适合运算密集型
Python提供的支持多进程的包,multiprocessing 使用时可以直接导入。
 
(1)cpu_count()统计本机cup个数
import multiprocessing
mu=multiprocessing
p=mu.cpu_count()
print (p)
 
(2)实例验证:
def worker(interval):
    time.sleep(interval)
    print ('hello lql')

if __name__=="__main__":
#----先创建对象
    p = multiprocessing.Process(target=worker, args=(5,))
#----启动进程
    p.start()
#----查看该进程是否运行
    print (p.is_alive())
#----设定执行时间如果进程响应时间超过设定时间则继续执行别的进程
    # p.join(timeout=2)
    # print ("end up")
#----查看进程名与pid
    print (p.name)
    print (p.pid)
创建对象:p = multiprocessing.Process(target=worker, args=(5,)) 调用process模块,target为执行的对象,args为响应时间。
启动进程:执行start函数
查看进程是否运行:执行 is_alive函数
使用join函数设定中断时间为2而对象内的运行时间为5所以先执行下面的输出:
执行一个对象,默认为process1
 
多进程实例:
import time
import multiprocessing
def worker(name,interval):
    print ('please start your show {0}'.format(name))
    time.sleep(interval)
    print ('now your time is end {0}'.format(name))
if __name__=="__main__":
    print ("the computers cpu is {0}".format(multiprocessing.cpu_count()))
    p1=multiprocessing.Process(target=worker,args=('lql',3))
    p2=multiprocessing.Process(target=worker,args=('lql1',4))
    p3=multiprocessing.Process(target=worker,args=('lql2',5))
    p1.start()
    p2.start()
    p3.start()
    for p in multiprocessing.active_children():
        print ('the process is {0} and is pid is {1}'.format(p.name,p.pid))

结果:

C:\Python27\python.exe E:/untitled/Mutil/M2.py
the computers cpu is 2
please start your show lql
the process is Process-2 and is pid is 9480
the process is Process-3 and is pid is 2060
the process is Process-1 and is pid is 9468
please start your show lql1
please start your show lql2
now your time is end lql
now your time is end lql1
now your time is end lql2

Process finished with exit code 0