Two ways to create the python process (and then record the study notes)
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__":
# 在windows环境下,开启进程必须在__name__ == "__main__"下面
p = Process(target=task,args=("常辛",)) # 创建一个进程对象
p.start() # 只是向操作系统发出一个开辟子进程的信号,然后就执行下一行了
# 这个信号操作系统接收到之后,会从内存中开辟一个子进程空间,然后在将主进程所有数据copy加载到子进程,然后再调用CPU去执行
# 开辟子进程开销是很大的
print("主开始")
time.sleep(1)
print("主结束")
# 所以永远会先执行主进程的代码
'''
主开始
常辛 is running
主结束
常辛 is gone
'''
# 开启进程的第二种方式
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
'''