day33
进程创建的两种方式
在windows环境下,开启进程必须在______name______ == "main"下面
p.start(): 只是向操作系统发出一个开辟子进程的信号,然后就执行下一行了。
这个信号操作系统接收到之后,会从内存中开辟一个子进程空间,然后再将主进程所有数据copy加载到子进程,然后再调用cpu去执行
开辟子进程开销是狠大的,所以永远会先执行主进程的代码
开启进程的第一种方式
from multiprocessing import Process
import time
def task(name):
print(f"{name} is running")
time.sleep(2)
print(f"{name} is gone")
if __name__ == '__main__':
p = Process(target=task, args=("常鑫", ))
p.start()
time.sleep(0.3)
print("===主开始")
开启进程的第二种方式
一
from multiprocessing import Process
import time
class MyProcess(Process):
def run(self):
print(f"{self.name} is running")
time.sleep(2)
print(f"{self.name} is gone")
if __name__ == '__main__':
p = MyProcess()
p.start()
print("===主")
结果:
===主
MyProcess-1 is running
MyProcess-1 is gone
二
from multiprocessing import Process
import time
class MyProcess(Process):
def __init__(self, name):
super().__init__()
self.name = name
def run(self):
print(f"{self.name} is running")
time.sleep(2)
print(f"{self.name} is gone")
if __name__ == '__main__':
p = MyProcess("常鑫")
p.start()
print("===主")
结果:
===主
常鑫 is running
常鑫 is gone
简单应用
from multiprocessing import Process
import time
def task(name):
print(f"{name} is running")
time.sleep(3)
print(f"{name} is gone")
def task1(name):
print(f"{name} is running")
time.sleep(1)
print(f"{name} is gone")
def task2(name):
print(f"{name} is running")
time.sleep(2)
print(f"{name} is gone")
if __name__ == '__main__':
# 一个进程串行的执行三个任务
# start_time = time.time()
# task("常鑫")
# task1("离远点也")
# task("海狗")
# print(f"结束时间{time.time() - start_time}")
# 三个进程 并发或者并行的执行三个任务
start_time = time.time()
p1 = Process(target=task, args=("常鑫",))
p2 = Process(target=task1, args=("离远点也",))
p1.start()
p2.start()
task2("海狗")
print(f"结束时间{time.time() - start_time}")
进程pid
-
如何区分内存中的这些进程
- 命令行获取所有的进程的pid tasklist
-
代码级别如果获取一个进程pid
import os print(os.getpid())
-
如何获取父进程(主进程)的pid?
import os
import time
print(f"子进程:{os.getpid()}")
print(f"主(父)进程:{os.getppid()})
time.sleep(50)
验证进程之间的空间隔离
from multiprocessing import Process
import os
import time
name = "太白"
def task():
global name
name = "刚子sb"
print(f"子进程:{name}")
if __name__ == '__main__':
p = Process(target=task)
p.start()
time.sleep(3)
print(f"主:{name}")
结果:
子进程:刚子sb
主:太白
from multiprocessing import Process
import os
import time
lst = ["丽丽"]
def task():
lst.append("怼姐")
print(f"子进程{lst}")
if __name__ == '__main__':
p = Process(target=task)
p.start()
time.sleep(3)
print(f"主:{lst}")
结果:
子进程['丽丽', '怼姐']
主:['丽丽']
进程对象join方法
join就是阻塞,主进程有join,join下面的代码一律不执行,直到子进程执行完毕之后再执行
单进程使用join
from multiprocessing import Process
import time
def task(name):
print(f"{name} is running")
time.sleep(2)
print(f"{name} is gone")
if __name__ == '__main__':
p = Process(target=task, args=("常鑫",))
p.start()
p.join()
print("===主开始")
结果:
常鑫 is running
常鑫 is gone
===主开始
多个子进程使用join
# 一
from multiprocessing import Process
import time
def task(name, sec):
print(f"{name} is running")
time.sleep(sec)
print(f"{name} is gone")
if __name__ == '__main__':
start_time = time.time()
p1 = Process(target=task, args=("常鑫",3))
p2 = Process(target=task, args=("李业",2))
p3 = Process(target=task, args=("海狗",1))
p1.start()
p2.start()
p3.start()
p1.join()
p2.join()
p3.join()
print(f"主:{time.time() - start_time}")
结果:
常鑫 is running
李业 is running
海狗 is running
海狗 is gone
李业 is gone
常鑫 is gone
主:3.1368300914764404
# 二
from multiprocessing import Process
import time
def task(name, sec):
print(f"{name} is running")
time.sleep(sec)
print(f"{name} is gone")
if __name__ == '__main__':
start_time = time.time()
p1 = Process(target=task, args=("常鑫", 1))
p2 = Process(target=task, args=("李业", 2))
p3 = Process(target=task, args=("海狗", 3))
p1.start()
p2.start()
p3.start()
p1.join()
print(f"p1:{time.time() - start_time}")
p2.join()
print(f"p2:{time.time() - start_time}")
p3.join()
print(f"主:{time.time() - start_time}")
结果:
常鑫 is running
李业 is running
海狗 is running
常鑫 is gone
p1:1.1349449157714844
李业 is gone
p2:2.14038348197937
海狗 is gone
主:3.1495747566223145
# 三
from multiprocessing import Process
import time
def task(name, sec):
print(f"{name} is running")
time.sleep(sec)
print(f"{name} is gone")
if __name__ == '__main__':
start_time = time.time()
p1 = Process(target=task, args=("常鑫", 3))
p2 = Process(target=task, args=("李业", 2))
p3 = Process(target=task, args=("海狗", 1))
p1.start()
p2.start()
p3.start()
p1.join()
print(f"p1:{time.time() - start_time}")
p2.join()
print(f"p2:{time.time() - start_time}")
p3.join()
print(f"主:{time.time() - start_time}")
结果:
常鑫 is running
李业 is running
海狗 is running
海狗 is gone
李业 is gone
常鑫 is gone
p1:3.1304543018341064
p2:3.1309428215026855
主:3.1309428215026855
面试题
# from multiprocessing import Process
# import time
#
# def task(name,sec):
# print(f'{name}is running')
# time.sleep(sec)
# print(f'{name} is gone')
#
#
# if __name__ == '__main__':
# start_time = time.time()
# p1 = Process(target=task,args=('常鑫',3))
# p2 = Process(target=task,args=('李业',2))
# p3 = Process(target=task,args=('海狗',1))
#
# p1.start()
# p2.start()
# p3.start()
# # join就是阻塞
#
# p1.join() # 等2s
# print(f'==主1:{time.time()-start_time}')
# p2.join()
# print(f'===主2:{time.time()-start_time}')
# p3.join()
# print(f'==主3:{time.time()-start_time}')
优化上面的代码
# 错误的示范
from multiprocessing import Process
import time
def task(sec):
print("is running")
time.sleep(sec)
print("is gone")
if __name__ == '__main__':
start_time = time.time()
for i in range(1,4):
p = Process(target=task, args=(i,))
p.start()
p.join()
print(f"总时间:{time.time() - start_time}")
# 正确的示范
from multiprocessing import Process
import time
def task(sec):
print("is running")
time.sleep(sec)
print("is gone")
if __name__ == '__main__':
l1 = []
start_time = time.time()
for i in range(1,4):
p = Process(target=task, args=(i,))
l1.append(p)
p.start()
for i in l1:
i.join()
print(f"总时间:{time.time() - start_time}")
进程对象其他属性
p.terminate():杀死子进程
p.is_alive():查看子进程是否存活,或者返回True,否则False
from multiprocessing import Process
import time
def task(name):
print(f"{name} is running")
time.sleep(2)
print(f"{name} is gone")
if __name__ == '__main__':
p = Process(target=task, args=("常鑫",))
# p = Process(target=task, args=("常鑫",), name="alex")
p.start()
# p.terminate()
print(p.is_alive())
# print(p.name) # alex
print("===主")
守护进程
例子:古时候,太监守护皇帝,如果皇帝驾崩了,太监直接也就死了。
子进程守护着主进程,只要主进程结束,子进程跟着就结束
from multiprocessing import Process
import time
def task(name):
print(f"{name} is running")
time.sleep(2)
print(f"{name} is gone")
if __name__ == '__main__':
p = Process(target=task, args=("常鑫",))
p.daemon = True # 将p子进程设置成守护进程,只要主进程结束,守护进程马上结束
p.start()
# p.daemon = True # 一定要在子进程开启之前设置
print("===主")
结果:===主
from multiprocessing import Process
import time
def task(name):
print(f"{name} is running")
time.sleep(2)
print(f"{name} is gone")
if __name__ == '__main__':
p = Process(target=task, args=("常鑫",))
p.daemon = True # 将p子进程设置成守护进程,只要主进程结束,守护进程马上结束
p.start()
# p.daemon = True # 一定要在子进程开启之前设置
time.sleep(1)
print("===主")
结果:
常鑫 is running
===主