爬虫-GIL与线程同步问题(11)

GIL的定义:

在CPython中,这个全局解释器锁,也称之为GIL,是一个互斥锁,防止多个线程。在同一时间执行python字节码,这个锁是非常重要的,
因为CPython的内存管理是非线程安全的,很多其他的特性依赖于GIL锁,所以即使它影响了程序效率也无法将其直接去除。

GIL的锁问题:

加锁的时机:在调用解释器时立即加锁

解锁时机:1.当前线程遇到了IO时释放。2.当前线程执行时间超过设定值时释放。

GIL的影响与避免:

1.单核下无论是IO密集还是计算密集GIL都不会产生任何影响

2.多核下对于IO密集任务,GIL会有细微的影响,基本可以忽略

3.Cpython中IO密集任务应该采用多线程,计算密集型应该采用多进程

加锁线程安全的实现代码:

from threading import Thread
from threading import Lock
#线程间同步
#库存

total = 0
total_lock = Lock()
def add():
    total_lock.acquire()
    global total
    for i in range(1000000):
        total += 1
    total_lock.release()

def desc():
    total_lock.acquire()
    global total
    for i in range(1000000):
        total -= 1
    total_lock.release()


if __name__ == "__main__":
    add_thread = Thread(target=add)
    desc_thread = Thread(target=desc)

    add_thread.start()
    desc_thread.start()

    add_thread.join()
    desc_thread.join()
    print(total)
好好学习,天天向上
原文地址:https://www.cnblogs.com/topass123/p/13341832.html