join方法:
# join方法
from multiprocessing import Process import time,os def task(): print('%s is running,parent id is <%s>' %(os.getpid(),os.getppid())) time.sleep(3) print('%s is done,parent id is <%s>'%(os.getpid(),os.getppid())) if __name__ == '__main__': p = Process(target=task) p.start() p.join() # 主进程在等 print('主',os.getpid(),os.getppid()) print(p.pid) # 获取p 的pid 并行运行时间为 等最长的那个进程执行完的时间 from multiprocessing import Process import time,os def task(name,n): print('%s is running' %name) time.sleep(n) if __name__ == '__main__': start = time.time() p1=Process(target=task,args=('子进程1',5)) p2=Process(target=task,args=('子进程2',3)) p3=Process(target=task,args=('子进程3',2)) p_l=[p1,p2,p3] # p1.start() # start 是发送信号 # p2.start() # p3.start() for p in p_l: p.start() # p1.join() # join 是等子进程运行完后,运行主进程。并发是等最长的时间的 # p2.join() # p3.join() for p in p_l: p.join() print('主',(time.time()-start)) # 此为并发执行,执行时间为最长的那个
并行改为串行:时间为单个相加之和 from multiprocessing import Process import time,os def task(name,n): print('%s is running' %name) time.sleep(n) if __name__ == '__main__': start=time.time() p1=Process(target=task,args=('子进程1',5)) p2=Process(target=task,args=('子进程2',3)) p3=Process(target=task,args=('子进程3',2)) p1.start() #p1启动,p2,p3压根没启动 p1.join() p2.start() p2.join() p3.start() p3.join() print('主',(time.time()-start)) # 此为单个的运行,时间为各个的加和,为10秒多
# 其他属性:is_alive from multiprocessing import Process import time,os def task(): print('%s is running,parent id is <%s>' %(os.getpid(),os.getppid())) time.sleep(3) print('%s is done,parent id is <%s>' %(os.getpid(),os.getppid())) if __name__ == '__main__': p = Process(target=task,) p.start() print(p.is_alive()) p.join() print('主',os.getpid(),os.getppid()) print(p.pid) #了解 : from multiprocessing import Process import time,os def task(): print('%s is running,parent is <%s>' %(os.getpid(),os.getppid())) time.sleep(3) print('%s is done,parent is <%s>' %(os.getpid(),os.getppid())) if __name__ == '__main__': p = Process(target=task,name='sub-Process') p.start() p.terminate() # 给操作系统发送终止信号 print(p.is_alive()) print('主') print(p.name)