python GIL (全局解释器锁)

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

GIL global interpreter lock

来自官方文档的解释

The mechanism used by the CPython interpreter to assure that only one thread executes Python bytecode at a time. This simplifies the CPython implementation by making the object model (including critical built-in types such as dict) implicitly safe against concurrent access. Locking the entire interpreter makes it easier for the interpreter to be multi-threaded, at the expense of much of the parallelism afforded by multi-processor machines.

However, some extension modules, either standard or third-party, are designed so as to release the GIL when doing computationally-intensive tasks such as compression or hashing. Also, the GIL is always released when doing I/O.

Past efforts to create a “free-threaded” interpreter (one which locks shared data at a much finer granularity) have not been successful because performance suffered in the common single-processor case. It is believed that overcoming this performance issue would make the implementation much more complicated and therefore costlier to maintain.

目的保证同一时间只有一个线程在执行保证线程安全

优势简化CPython解释器的实现

劣势多线程无法做到真正的并行无法利用多核CPU的优势由于GIL锁的存在同一时刻只有获得GIL锁的线程才能被执行。

对编程的影响

因为GIL锁只有在线程时间片用完或者遇到I/O操作才会被释放所以对于计算密集型的任务需要长时间占用CPU的应当使用多进程。对于I/O密集的任务推荐使用多线程因为线程的切换代价小。

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: python