多进程典型案例:
1、将子进程的进程名作为列表中的元素,在父进程中遍历(异步)执行
#coding: utf-8 from multiprocessing import Pool import os, time, random #将函数打包成列表中的元素,再(异步)遍历执行 def zhangsan(): print (" Run task 张三-%s" %(os.getpid())) #os.getpid()获取当前的进程的ID start = time.time() time.sleep(random.random() * 10) #random.random()随机生成0-1之间的小数 end = time.time() print ('Task 张三 runs %0.2f seconds.' %(end - start)) def lisi(): print (" Run task 李四-%s" %(os.getpid())) start = time.time() time.sleep(random.random() * 40) end=time.time() print ('Task 李四 runs %0.2f seconds.' %(end - start)) def wangwu(): print (" Run task 王五-%s" %(os.getpid())) start = time.time() time.sleep(random.random() * 30) end = time.time() print ('Task 王五 runs %0.2f seconds.' %(end - start)) def zhaoliu(): print (" Run task 赵六-%s" %(os.getpid())) start = time.time() time.sleep(random.random() * 20) end = time.time() print ('Task 赵六 runs %0.2f seconds.' %(end - start)) if __name__=='__main__': function_list= [zhangsan, lisi, wangwu, zhaoliu] print ("parent process %s" %(os.getpid())) pool=Pool(4) for func in function_list: pool.apply_async(func) #Pool执行函数,apply执行函数,当有一个进程执行完毕后,会添加一个新的进程到pool中 print ('等待所有子进程执行……') pool.close() ''' 调用join之前,一定要先调用close() 函数,否则会出错, close()执行后不会有新的进程加入到pool,join函数等待素有子进程结束 ''' pool.join() print ('子进程执行完毕')