今天用面向对象写了一段代码,用创建的类重构父类的方法,实现函数锁能实现的功能:代码如下
1 from os import getpid 2 from time import sleep 3 from multiprocessing import Process 4 5 6 class MyProcess(Process): 7 8 def __init__(self, args): 9 super(MyProcess, self).__init__() 10 self.args = args 11 12 def run(self): 13 print('Process ID is %s' % getpid()) 14 print('Process %s has been executed ' % self.args) 15 16 def start(self): 17 print('Process %s will be executed ' % self.args) 18 super().start() 19 20 def terminate(self): 21 super().terminate() 22 23 def join(self, timeout=None): 24 super().join() 25 26 def is_alive(self): 27 super().is_alive() 28 29 30 if __name__ == '__main__': 31 process_list = [] 32 for i in range(10): 33 p = MyProcess(i) 34 p.start() 35 print(p.is_alive()) 36 process_list.append(p) 37 for p in process_list: 38 print(p.is_alive()) 39 print('There will terminated process %s' % p) 40 p.terminate() 41 sleep(0.2) # 这里不延时0.2而直接打印的话,下边的is_alive会显示True 42 print(p.is_alive()) 43 p.join() 44 print(p.is_alive())