# 多进程调用(大部分与多线程的操作一样)
# 调用方式1
from multiprocessing import Process
import time
def f(name):
time.sleep(1)
print('hello', name, time.ctime())
if __name__ == '__main__':
p_list = []
for i in range(3):
p = Process(target=f, args=('alex',))
p_list.append(p)
p.start()
for i in p_list:
i.join()
print('end')
# 调用方式2
from multiprocessing import Process
import time
class MyProcess(Process):
# def __init__(self):
# super(MyProcess, self).__init__()
# self.name = name
def run(self):
time.sleep(1)
print('hello', self.name, time.ctime())
if __name__ == '__main__':
p_list = []
for i in range(3):
p = MyProcess()
# p.daemon = True # 设置守护进程
p.start()
p_list.append(p)
# for i in p_list:
# i.join()
print('end...')
# 查看进程的pid
from multiprocessing import Process
import os, time
def info(title):
print('title:', title)
print('parent process:', os.getppid())
print('process id:', os.getpid())
def f(name):
info('function f')
print('hello', name)
if __name__ == '__main__':
info('main process line')
time.sleep(1)
print('-' * 30)
p = Process(target=info, args=('alex',))
p.start()
p.join()
# title: main process line
# parent process: 1792 # 父进程的进程pid(pycharm)
# process id: 4116 # 当前.py文件运行的pid
# ------------------------------
# title: alex
# parent process: 4116 # 父进程的pid即当前.py文件运行的pid
# process id: 6392 # 产生的子进程的pid
# Process类的方法与属性
# 构造方法:
# Process(group[, target[, name[, args[, kwargs]]]])
# group: 线程组,目前还没有实现,库引用中提示必须是None
# target: 要执行的方法
# name: 指定进程名
# args / kwargs: 要传入方法的参数
#
# 实例方法:
# is_alive() 返回进程是否在运行
# join([timeout]) 阻塞当前上下文环境的进程,直到调用此方法的进程终止或到达指定的timeout
# start() 进行准备就绪,等待cpu调度
# run() start()方法调用run方法,如果实例进程时未制定传入target,这start执行默认run方法
# terminate() 不管任务是否完成,立即停止工作进程
#
# 属性:
# daemon 和线程的setDaemon功能一样
# name 进程名字
# pid 进程号
from multiprocessing import Process
import time
class MyProcess(Process):
def __init__(self, num):
super(MyProcess, self).__init__()
self.num = num
def run(self):
time.sleep(1)
print(self.is_alive(), self.num, self.pid)
time.sleep(1)
if __name__ == '__main__':
p_list = []
for i in range(10):
p = MyProcess(i)
p_list.append(p)
for p in p_list:
p.start()
print('main process end')