from multiprocessing import Process import time def task(interval): time.sleep(interval) print('我是子进程') if __name__ == '__main__': print('主进程开始') p = Process(target=task,args=(1,)) p.start() print('主进程结束')
####################################
from multiprocessing import Process import time import os def child_1(interval): print('子进程%s开始执行,它的父进程是%s'%(os.getpid(),os.getppid())) t_start = time.time() time.sleep(interval) t_end=time.time() print('子进程%s执行时间为%0.2f秒'%(os.getpid(),t_end-t_start)) def child_2(interval): print('子进程%s开始执行,它的父进程是%s'%(os.getpid(),os.getppid())) t_start = time.time() time.sleep(interval) t_end=time.time() print('子进程%s执行时间为%0.2f秒'%(os.getpid(),t_end-t_start)) if __name__ == '__main__': print('主进程开始') print('主进程pid:%s'%os.getpid()) p1 = Process(target=child_1, args=(1,)) p2 =Process(target=child_2,name='mrsoft',args=(2,)) p1.start() p2.start() print('p1.is_alive:%s'%p1.is_alive()) print('p2.is_alive:%s'%p2.is_alive()) print('p1.name:%s'%p1.name) print('p1.id:%s'%p1.pid) print('p2.name:%s' % p2.name) print('p2.id:%s' % p2.pid) p1.join() p2.join() print('主进程结束')
################################################
from multiprocessing import Pool import os import time def task(name): print('子进程%s执行任务%s'%(os.getpid(),name)) time.sleep(1) if __name__ == '__main__': print('父进程%s'%os.getpid()) p=Pool(3) for i in range(10): p.apply_async(task,args=(i,)) p.close() p.join() print('所有子进程结束')