并发编程 ~~~ 多进程~~~进程创建的两种方式, 进程pid, 验证进程之间的空间隔离, 进程对象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__':
#在windows环境下, 开启进程必须在 __name__ == '__main__' 下面
p = Process(target=task,args=('常鑫',))
p.start()
print('主进程开始')
time.sleep(3)
print('主进程结束')
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() # 启动的是类里面的run方法
print('主进程')
二 进程pid
import os
import time
print(f'子进程:{os.getpid()}')
print(f'主(父)进程:{os.getppid()}')
time.sleep(50)
三 验证进程之间的空间隔离
from multiprocessing import Process
import time
name = '小虎'
lst = [1,2,3]
def task():
global name
name = '海狗'
lst.append(4)
print(f'子进程{name}')
print(f'子进程{lst}')
if __name__ == '__main__':
p = Process(target=task)
p.start()
time.sleep(2)
print(f'主进程{name}')
print(f'主进程{lst}')
# 子进程海狗
# 子进程[1, 2, 3, 4]
# 主进程小虎
# 主进程[1, 2, 3]
主进程和子进程之间是隔离的
四 进程对象join方法
join让主进程等待子进程结束之后,在执行主进程.
from multiprocessing import Process
import time
def task(sec):
print('running')
time.sleep(sec)
print('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()
p2.join()
p3.join()
print(time.time() - start_time)
# 优化上面代码:
lst =[]
for i in range(1,4):
p = Process(target=task,args=(i,))
lst.append(p)
p.start()
for k in lst:
k.join()
print(time.time() - start_time)
五 进程对象其他属性
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=('大黑',),name='进程1')
p.start()
time.sleep(1)
p.terminate() # 杀死子进程
p.join() # 让主进程等待子进程结束之后,在执行主进程.
print(p.is_alive()) # 判断子进程是不是还在运行
print(p.name) # 进程的名字
p.name = '小虎'
print(p.name)
print('主进程')