python-GIL

全局解释器锁GIL:在同一时刻仅有一个线程可被调度执行。对于单核环境,该实现简单高效。对于多线程的并发应用,一般通过多进程加协程充分发挥多核计算能力。

对于I/O密集型任务,线程发生阻塞时,会自动释放GIL锁,以便其他进程执行。所以 I/O密集型适合使用多线程

对于CPU执行,任务则采用超时策略。

网络I/O密集型的多线程与单线程比较:(计算cpu密集型只能通过多进程改善或者是通过C来编写多线程以便绕过GIL,此例是测试的I/O密集型)

import threading
import requests
import sys


def task():
    """ 网络I/O """
    result = requests.get('http://source.unsplash.com/random')  # status_code
    with open(f"{str(uuid.uuid1().hex)}.jpg", 'wb') as f:
        f.write(result.content)
    return result

print(sys.argv)
if len(sys.argv)>1:
    ts = [threading.Thread(target=task) for i in range(10)]
    for t in ts: t.start()
    for t in ts: t.join()
else:
    [task() for i in range(10)]

>>>
(djProj_py3) appledeMacBook-Air-7:practice apple$ time python ff.py  a  # 线程启动
['ff.py', 'a']

real    0m13.583s
user    0m0.565s
sys     0m0.110s
(djProj_py3) appledeMacBook-Air-7:practice apple$ time python ff.py   # 非线程启动
['ff.py']

real    0m39.777s
user    0m0.566s
sys     0m0.112s
原文地址:https://www.cnblogs.com/tangpg/p/9585378.html