Python从0到1:GIL全局解释器锁

上篇文章《Python从0到1:threading多线程编程》提及一个名词全局解释器锁GIL,很多Python爱好者私信给我说不理解它的原理,今天就对GIL单独分享一下。

先看官方给出的解释:In CPython, the global interpreter lock, or GIL, is a mutex that prevents multiple native threads from executing Python bytecodes at once. This lock is necessary mainly because CPython’s memory management is not thread-safe. (However, since the GIL exists, other features have grown to depend on the guarantees that it enforces.)从官方的定义来看,GIL无疑就是一把对多线程有影响的全局锁,解决它对多线程的影响,不单单是释放GIL这么简单。

GIL使得对象模型都是可以并发访问。GIL全局解释器锁解决多线程之间数据完整性和状态同步的问题,但是这个锁在同一时刻只有一个线程在运行,所以在多核的情况下也只能发挥出单核的性能,多线程依旧像是单线程的运行。下面用一个单线程和多线程对比实例给大家看一下结果。

# -*- coding:utf-8 -*-

# __author__'zhuxuemin'

from threading import Thread

import time

def counter():

i = 0

for i in range(50000):

i += 1

return True

def single_thread():

start_time = time.time()

for tid in range(2):

t = Thread(target=counter)

t.start()

t.join()

end_time = time.time()

print ("total time of single is: {}".format(end_time - start_time))

def multi_thread():

thread_all = []

start_time = time.time()

for tid in range(2):

t = Thread(target=counter)

t.start()

thread_all.append(t)

for i in range(2):

thread_all[i].join()

end_time = time.time()

print ("total time of multi is: {}".format(end_time -start_time))

if __name__ == '__main__':

single_thread()

multi_thread()

执行结果:

total time of single is: 0.04100227355957031

total time of multi is: 0.019001245498657227

科学集团电子商务

IT业务一站式技术服务

  • 发表于:
  • 原文链接:http://kuaibao.qq.com/s/20171216G010XW00?refer=cp_1026

扫码关注云+社区