注意:
# 载入时间模块,random模块
import time
#获取开始时间结束时间
start=time.time()
#创建1个随机数
time.sleep(random.random()*3)
end=time.time()
#运行时间
t=end-start
****__name__是当前模块名,当前模块被直接运行时模块名为__main__
if __name__ == '__main__'
相当于是python的模拟程序入口 ,
如果模块是直接被运行的 则下面的代码块将被运行,如果模块是被导入的,则代码块不被运行
【Linux】
os模块封装了常见的系统调用
os.getpid()-->获取进程id
os.fork()----->生成2个进程(父&子:父返回子进程id,子进程永远返回0)
【Windows】
multiprocessing模块提供一个process类代表一个进程对象
from multiprocessing import Process
import os
# 子进程要执行的代码
def run_proc(name):
print('Run child process %s (%s)...' % (name, os.getpid()))
if __name__=='__main__':
print('Parent process %s.' % os.getpid())
p = Process(target=run_proc, args=('test',))
print('Child process will start.')
p.start()
p.join()
print('Child process end.')
【进程池Pool】
#同时跑5个进程
p=Pool(5)
【进程间通信】
交换数据:Queue,Pipes等
from multiprocessing import Process,Queue
import os,time,random
#写数据进程执行代码
def write(q):
print('Process to write:%s'%os.getpid())
for value in ['A','B','C']:
print('put %s to queue'%value)
q.put(value)
time.sleep(random.random())
#读数据进程执行代码
def read(q):
print('Process to read:%s'%os.getpid())
while True:
value=q.get(True)
print('get %s from queue'%value)
if __name__=='__main__':
#父进程创建Queue,并传给各个子进程
q=Queue()
pw=Process(target=write,args=(q,))
pr=Process(target=read,args=(q,))
#启动子进程pw 写入
pw.start()
#启动子进程pr 读取
pr.start()
#等待pw结束
pw.join()
#pr进程里时死循环 无法等待结束 只能强行终止
pr.terminate()