前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python从0到1:GIL全局解释器锁

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

作者头像
企鹅号小编
发布2018-02-28 10:36:02
9080
发布2018-02-28 10:36:02
举报
文章被收录于专栏:企鹅号快讯企鹅号快讯

上篇文章《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业务一站式技术服务

本文来自企鹅号 - 科学集团电子商务媒体

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文来自企鹅号 - 科学集团电子商务媒体

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档