一、个小院里:
① 启动python解释器(软件),软件的代码在硬盘上;问:写的python程序能执行吗?
② 把硬盘上的代码读到内存上,python解释器起来了(C代码);
③ 用python解释器再到硬盘吧test.py 读到内存(python代码);
④ C代码,python代码都在一个进程里边,线程都能看到。
解:不能,离开python解释器,代码啥都不是,必须依赖python解释器。
二、
GIL(进程与线程的应用场景) *****
1、每一个cpython进程内都有一个GIL
2、GIL导致同一进程内的多个线程同一时间只能有一个运行
3、之所以有GIL,是因为Cpython的内存管理不是线程安全的
4、对于计算密集型用多进程,多IO密集型用多线程
多进程(多核) :金融② I/O 密集型:
一个线程一个锁。
1.多线程(不用多核):爬虫
2.协程
同一进程只有一个线程能运行。
1. 计算密集型:多进程效率高
from multiprocessing import Process
from threading import Thread
import os,time
def work():
res=0
for i in range(10000000):
res*=i
if __name__ == '__main__':
l=[]
print(os.cpu_count()) #本机为4核
start=time.time()
for i in range(4):
p=Process(target=work) #耗时run time is 2.285580635070801
# p=Thread(target=work) #耗时run time is 2.770967960357666
l.append(p)
p.start()
for p in l:
p.join()
stop=time.time()
print('run time is %s' %(stop-start))
2 . I/O密集型:线程效率高
from multiprocessing import Process
from threading import Thread
import os,time
def work():
time.sleep(2)
if __name__ == '__main__':
l=[]
start=time.time()
for i in range(100):
p=Process(target=work) #耗时run time is 11.310112476348877
# p=Thread(target=work) #耗时run time is 2.0168063640594482
l.append(p)
p.start()
for p in l:
p.join()
stop=time.time()
print('run time is %s' %(stop-start))
骚灵情歌 --- 张敬轩