day10-多进程的基本语法
一、概述
之前我们了解的线程,接下来我们学习多进程,进程之间是相互独立的,python是启动进程的时候,是启动的是原生进程。进程是没有GIL锁的,而且不存在锁的概念,进程之间的数据式不能共享的,而线程是可以的。
英文解释如下:
multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine. It runs on both Unix and Windows.
二、线程的使用场景
2.1、使用场景
- IO操作:不占用cpu的操作,比如:从磁盘上读块数据,从网络读块数据,从内存上读块数据都算是io的操作。
- 计算是占用cpu的,比如:计算1+1。线程利用上下文切换,也是消耗资源的。如果大量计算,用多线程就不快了,线程之前的来回切换,运算不要用。
- python的多线程不适合cpu的密集型操作的任务。但是,适合io密集型的任务,比如:socket_server 的使用。
三、进程
3.1、进程的定义
说明:用muliprocessing这个包中的Process来定义多进程,跟定义多线程差不多。
from multiprocessing import Process #导入进程模块
import time
def run(name):
time.sleep(2)
print("hello",name)
if __name__ == "__main__":
p_obj_list = list() #存放进程对象
for i in range(10): #启动10个进程
p = Process(target=run,args=("qigao{0}".format(i),)) #产生一个进程实例
p.start() #启动进程
p_obj_list.append(p)
for p in p_obj_list:
p.join() #等待进程结果
3.2、进程中嵌入线程
说明:在进程中去嵌入线程
from multiprocessing import Process
import time,threading
def thead_run(name): #定义线程执行的方法
print("{0}:{1}".format(name,threading.get_ident()))
def run(name):
time.sleep(2)
print("hello",name)
t = threading.Thread(target=thead_run,args=(name,)) #嵌入线程
t.start() #执行线程
if __name__ == "__main__":
p_obj_list = list()
for i in range(10):
p = Process(target=run,args=("qigao{0}".format(i),))
p.start()
p_obj_list.append(p)
for p in p_obj_list:
p.join()
3.3、父子进程
说明:每个子进程都是由一个父进程启动的,即便是我们这种程序也是有一个父进程的。
from multiprocessing import Process
import os
def info(title):
print(title)
print('module name:', __name__)
print('parent process:', os.getppid())
print('process id:', os.getpid())
print("\n\n")
def f(name):
info('\033[31;1mfunction f\033[0m')
print('hello', name)
if __name__ == '__main__':
info('\033[32;1mmain process line\033[0m')
p = Process(target=f, args=('bob',))
p.start()
p.join()
执行的结果:

总结:
在Linux上执行这个父进程就是terminal自己,init 0所有的进程都是它启动的。

浙公网安备 33010602011771号