上一节我们使用multiprocessing创建了进程,这一节看一下使用进程类的方式进程创建进程;
- 需要继承Process类
from multiprocessing import Process
class MyProcess(Process):
def run(self):
with open('test.txt','a',encoding='utf8') as f:
for i in range(2):
f.write('python-')
if __name__ == '__main__':
for i in range(2):
MyProcess().start()
运行结果:
目录下生成test.txt
python-python-python-python-
增加参数:
需要在__init__方法中继承父类的__init__方法;
super().__init__()
from multiprocessing import Process
class MyProcess(Process):
def __init__(self,file):
super().__init__()
self.file = file
def run(self):
with open(self.file,'a',encoding='utf8') as f:
for i in range(2):
f.write('java-')
if __name__ == '__main__':
for i in range(2):
MyProcess('test1.txt').start()
运行结果:
生成的test1.txt文件:
java-java-java-java-