day9-多进程的基本语法
概述
我们之前了解了多线程,现在我们来了解下多进程,它是使用的是操作系统的原生进程,原生进程是操作系统自己维护的,因为进程间不能够相互访问,所以没有锁的概念,如果我的电脑是8核,我运行8个进程,同时在每个进程运行一个线程,那么这时,就有8线程了,充分利用多核,唯一的缺点是这8个线程之间的数据不共享,是独立的。
多线程的使用场景
- IO操作不占用CPU,计算占用CPU,Python多线程是执行上下文的切换,不是真正的多线程
- 多线程不适合cpu密集操作型的任务,适合IO密集型的任务。那么如此说来,对于CPU密集型的操作,我们使用什么呢?使用多进程
多进程
用法:使用multiprocessing模块来定义多进程
import multiprocessing # 导入多进程模块
import time
def run(name):
time.sleep(2)
print('hello', name)
if __name__ == '__main__':
p_obj = [] # 存放进程对象
for i in range(10): #启动10个进程
p = multiprocessing.Process(target=run, args=('bob %s' % i,)) # 生成多进程的实例
p.start() # 启动多进程
p_obj.append(p)
for p in p_obj:
p.join() # 等待进程执行结束
#运行输出
hello bob 0
hello bob 1
hello bob 2
hello bob 3
hello bob 4
hello bob 5
hello bob 6
hello bob 7
hello bob 8
hello bob 9
Process finished with exit code 0
进程中嵌入线程
import multiprocessing,threading
import time
def thread_run():
print(threading.get_ident())
def run(name):
time.sleep(2)
print('hello', name)
t = threading.Thread(target=thread_run(),) #进程中嵌入线程
t.start()
if __name__ == '__main__':
p_obj = []
for i in range(10):
p = multiprocessing.Process(target=run, args=('bob %s' %i,))
p.start()
p_obj.append(p)
for p in p_obj:
p.join()
#运行输出
hello bob 0
4320621376
hello bob 1
4320621376
hello bob 2
4320621376
hello bob 3
4320621376
hello bob 4
4320621376
hello bob 5
4320621376
hello bob 6
4320621376
hello bob 7
4320621376
hello bob 8
4320621376
hello bob 9
4320621376
Process finished with exit code 0
父进程与子进程的关系
from multiprocessing import Process
import os
def info(title):
print(title)
print('module name:', __name__)
print('parent process:', os.getppid()) #获取父进程ID
print('process id:', os.getpid()) #获取进程ID
print("\n\n")
def f(name):
info('\033[31;1mcalled from child process function f\033[0m') #调用info函数
print('hello', name)
if __name__ == '__main__':
info('\033[32;1mmain process line\033[0m')
p = Process(target=f, args=('bob',)) #生成f函数的进程实例
p.start()
p.join() #等待执行进程完毕
#运行输出

解析:可以看出每一个子进程都是由它的父进程启动的

浙公网安备 33010602011771号