python创建进程的两种方式

时间:2022-06-23 09:13:43

1.方式1

import time
import multiprocessing def task(arg):
time.sleep(2)
print(arg) def run():
# 进程1
p1 = multiprocessing.Process(target=task, args=(1,))
p1.name = 'pp1'
p1.start() # 进程2
p2 = multiprocessing.Process(target=task, args=(2,))
p2.name = 'pp2'
p2.start() if __name__ == '__main__':
run()

2.方式2

import multiprocessing

class MyProcess(multiprocessing.Process):
def run(self):
print('当前进程', multiprocessing.current_process()) def run():
p1 = MyProcess()
p1.start() p2 = MyProcess()
p2.start() if __name__ == '__main__':
run()