子进程基本使用
from multiprocessing import Process
import time
import os
def task(name):
print('pid %s: %s is running, and its parent pid: %s ' % (os.getpid(), name, os.getppid()))
time.sleep(3)
print('%s is done' % name)
class MyProcess(Process):
def __init__(self, name):
super(MyProcess, self).__init__()
self.name = name
def run(self):
print('pid %s: %s is running, and its parent pid: %s' % (os.getpid(), self.name, os.getppid()))
time.sleep(2)
print('%s is done' % self.name)
# Windows系统,置于if之下
if __name__ == '__main__':
# 开启子进程是为了执行一个任务
# 得到了一个对象 p
p = Process(target=task, args=('子进程1', ))
# 应用程序自己是开不了进程的,得给OS发信号,让OS来申请内存空间
p.start() # 运行时间和print差不多
# 类继承的使用方式
my_process = MyProcess('子进程2')
my_process.start()
print('主 pid: %s, and its parent pid: %s' % (os.getpid(), os.getppid()))
# tasklist | findstr pycharmLast updated