开启子进程的两种方式:
1、使用Process类
from multiprocessing import Process import time,os def f(name): print(‘%s is running,parent id is <%s>‘%(os.getpid(),os.getppid()),time.ctime()) time.sleep(1) print(‘%s is done‘ % os.getpgid(), time.ctime()) if __name__ == ‘__main__‘: p_list=[] for i in range(3): p = Process(target=f, args=(‘子进程%s‘%i,)) # p = Process(target=f,kwargs={‘name‘:‘子进程%s‘%i}) p_list.append(p) p.start() # 仅仅是给操作系统发送了一个信号 print(‘主进程‘,os.getpid()) for i in p_list: p.join() print(‘end‘)
2、写子类继承Process类
from multiprocessing import Process import time class MyProcess(Process): def __init__(self,name): super(MyProcess, self).__init__() self.name = name def run(self): print(‘%s is running‘ % self.name, time.ctime()) time.sleep(1) print(‘%s is done‘ % self.name, time.ctime()) if __name__ == ‘__main__‘: p_list=[] for i in range(3): p = MyProcess(‘子进程%d‘%i) p.start() p_list.append(p) for p in p_list: p.join() print(‘end‘)