code
import os from multiprocessing import Process class MyProcess(Process): def __init__(self,name): super().__init__() self.name=name def run(self): print(os.getpid()) print('%s 正在和女主播聊天' %self.name) p1=MyProcess('wupeiqi') p2=MyProcess('yuanhao') p3=MyProcess('nezha') p1.start() # start会自动调用run,p2.run() p2.start() p3.start() p1.join() p2.join() p3.join() print(os.getpid()) print('主线程')
outputs
macname@MacdeMacBook-Pro py % python3 cccccc.py 57134 wupeiqi 正在和女主播聊天 57135 yuanhao 正在和女主播聊天 57136 nezha 正在和女主播聊天 57133 主线程 macname@MacdeMacBook-Pro py %
code
import os import time import random from multiprocessing import Process def work(n): print('%s: %s is running' %(n,os.getpid())) time.sleep(random.random()) print('%s:%s is done' %(n,os.getpid())) if __name__ == '__main__': for i in range(3): p=Process(target=work,args=(i,)) p.start()
outputs
macname@MacdeMacBook-Pro py % python3 cccccc.py 0: 57174 is running 1: 57175 is running 2: 57176 is running 0:57174 is done 1:57175 is done 2:57176 is done macname@MacdeMacBook-Pro py %