Python 学习笔记(六)-
1.自定义进程
自定义进程类,继承Process类,重写run方法(重写Process的run方法)。
from multiprocessing import Process
import time
import os
class MyProcess(Process):
def __init__(self, name): ##重写,需要__init__,也添加了新的参数。
##Process.__init__(self) 不可以省略,否则报错:AttributeError:"XXXX"object has no attribute "_colsed"
Process.__init__(self)
self.name = name
def run(self):
print("子进程(%s-%s)启动" % (self.name, os.getpid()))
time.sleep(3)
print("子进程(%s-%s)结束" % (self.name, os.getpid()))
if __name__ == "__main__":
print("父进程启动")
p = MyProcess("Ail")
# 自动调用MyProcess的run()方法
p.start()
p.join()
print("父进程结束")
# 输出结果
父进程启动
子进程(Ail-38512)启动
子进程(Ail-38512)结束
父进程结束


