SlideShare ist ein Scribd-Unternehmen logo
1 von 24
gil那些事儿
峰云就她了
http://xiaorui.cc
相关
什么是python解释器
CPython vs pypy vs Jython
gil
什么是 Global Interpreter Lock
Python为什么会有gil
gil的优缺点
关于gil的历史
Thread A Thread B
O| | | | | | |-1
1. get the current length
2. check if there’s room for more
3. Append element
4. Incrment the length by 1
Python’ s 线程
python线程是系统线程的.
POSIX threads (pthreads)
Windows threads
受内核来调度并切换上下文
性能对比
def go_count(n):
while n > 0:
n -= 1
COUNT = 100000000 # 100 million
go_count(COUNT)
t1 = Thread(target=go_count,args=(COUNT//2,))
t2 = Thread(target=go_count,args=(COUNT//2,))
t1.start(); t2.start()
t1.join(); t2.join()
thread only
thread two
cost 10s
cost 21s
那么问题来了
多线程为什么比单线程还慢 ?
python解释器运行原理
只有一个线程在running
多线程acquire lock的消耗成本
gil
简单描述:
拿到gil锁,谁就可以running , 当释放gil, send signal
没拿到gil锁, 休眠. 内核调度到你, 你如果没锁, sleep and wait for a signal
什么时候释放锁:
IO Block
every 100 tick force, default
gil 是mutex + semaphore + condition
check_connection(self);
Py_BEGIN_ALLOW_THREADS
r = mysql_real_query(&(self->connection), query, len);
Py_END_ALLOW_THREADS
_mysql.c gil process
scheduler I/O
I/O I/O I/O I/O
run run run run
acquire
release
acquire
release
acquire
release
release
acquire
scheduler counter
c
h
e
c
k
run 100 ticks
run 100 ticks run 100 ticks
acquire release release
release
acquire
c
h
e
c
k
c
h
e
c
k
Change it using sys.setcheckinterval()
acquire
what a check
Periodic “check” is simple
The currently running thread …
reset the tick counter
run signal handler if this is main thread
relase the gil
Reacquires the gil
A tick ?
def go():
a = True
for i in range(3):
print i
if a:
print "xiaorui.cc"
b = None
c = 123
wake up
Condition Variable
等待wake up的线程队列enqueue
dequeuesignal
thread 5
thread 3
thread 2
thread 7
thread 1
t2 100 5351 ENTRY
t2 100 5351 ACQUIRE
t2 100 5352 RELEASE
t2 100 5352 ENTRY
t2 100 5352 ACQUIRE
t2 100 5353 RELEASE
t1 100 5353 ACQUIRE
t2 100 5353 ENTRY
t2 38 5353 BUSY
t1 100 5354 RELEASE
t1 100 5354 ENTRY
t1 100 5354 ACQUIRE
t2 79 5354 RETRY
t1 100 5355 RELEASE
t1 100 5355 ENTRY
t1 100 5355 ACQUIRE
t2 73 5355 RETRY
t1 100 5356 RELEASE
t2 100 5356 ACQUIRE
t1 100 5356 ENTRY
t1 24 5356 BUSY
t2 100 5357 RELEASE
进入临界区
获取锁
释放锁
没拿到锁
重新尝试
break to think
python如何保证listdict的操作原子性
某个线程一直高比率拿到锁 ?
t1时间片用完了, kernel把t2调度起来, 但gil还在t1手里 ?
多线程都在一个cpu core上 ?
suspended
100 tciks
check
os
signal
wake
release
不公平竞争
100 tciks
check
signal
suspended
100 tciks
T1
T2
thread
cs
……
不公平竞争
Thread A (cpu 1)
多核
Thread B (cpu 2)
release gil
acquire gil
release gil
acquire gil
waked
acquire gil (fail)
waked
acquire gil (fail)
signale
signale
suspended
100 tciks
check
new gil
100 tciks
T1
T2
cv_wait(gil,TIMEOUT)
timeout
signale
suspended
100 tciks
gil_drop_request = 1 gil_drop_request = 0
cv_wait(gil,TIMEOUT)
那么threading场景
由于有gil全局锁, python多线程的意义 ?
IO 密集
CPU 密集
python的线程调度策略
再次声明,解释器没有thread调度器
特例, Signal
当信号到达的时,解释器会按照每个tick都要check. 直到main thread处
理了signal.
绕过gil
multiprocessing
python gil 存在于线程之间
ctypes
调用c函数之前, 会释放gil
more … …
kill gil
python能否去掉gil ?
如何实现python底层去gil ?
去掉之后又会出现什么 ?
总结: 值不值, 成本 ?
“Q & A”
–峰云就她了

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (16)

Crypto theory to practice
Crypto theory to practiceCrypto theory to practice
Crypto theory to practice
 
Instruction Combine in LLVM
Instruction Combine in LLVMInstruction Combine in LLVM
Instruction Combine in LLVM
 
CNIT 141: 9. Elliptic Curve Cryptosystems
CNIT 141: 9. Elliptic Curve CryptosystemsCNIT 141: 9. Elliptic Curve Cryptosystems
CNIT 141: 9. Elliptic Curve Cryptosystems
 
Chapter 3 Commands at MATLAB Command Window
Chapter 3 Commands at MATLAB Command WindowChapter 3 Commands at MATLAB Command Window
Chapter 3 Commands at MATLAB Command Window
 
Machine Trace Metrics
Machine Trace MetricsMachine Trace Metrics
Machine Trace Metrics
 
keeloq-final
keeloq-finalkeeloq-final
keeloq-final
 
Code GPU with CUDA - Identifying performance limiters
Code GPU with CUDA - Identifying performance limitersCode GPU with CUDA - Identifying performance limiters
Code GPU with CUDA - Identifying performance limiters
 
Goroutine stack and local variable allocation in Go
Goroutine stack and local variable allocation in GoGoroutine stack and local variable allocation in Go
Goroutine stack and local variable allocation in Go
 
Gameboy emulator in rust and web assembly
Gameboy emulator in rust and web assemblyGameboy emulator in rust and web assembly
Gameboy emulator in rust and web assembly
 
Weka วิเคราะห์ 55102011029
Weka วิเคราะห์ 55102011029Weka วิเคราะห์ 55102011029
Weka วิเคราะห์ 55102011029
 
Monero Presentation by Justin Ehrenhofer - Cologne, Germany 2017
Monero Presentation by Justin Ehrenhofer - Cologne, Germany 2017Monero Presentation by Justin Ehrenhofer - Cologne, Germany 2017
Monero Presentation by Justin Ehrenhofer - Cologne, Germany 2017
 
[Question Paper] Linux Administration (75:25 Pattern) [November / 2014]
[Question Paper] Linux Administration (75:25 Pattern) [November / 2014][Question Paper] Linux Administration (75:25 Pattern) [November / 2014]
[Question Paper] Linux Administration (75:25 Pattern) [November / 2014]
 
Intro to python for data science course
Intro to python for data science courseIntro to python for data science course
Intro to python for data science course
 
00.cnn basic
00.cnn basic00.cnn basic
00.cnn basic
 
Make A Shoot ‘Em Up Game with Amethyst Framework
Make A Shoot ‘Em Up Game with Amethyst FrameworkMake A Shoot ‘Em Up Game with Amethyst Framework
Make A Shoot ‘Em Up Game with Amethyst Framework
 
Head First Java Chapter 5
Head First Java Chapter 5Head First Java Chapter 5
Head First Java Chapter 5
 

Andere mochten auch (6)

美妙的多进程管理
美妙的多进程管理美妙的多进程管理
美妙的多进程管理
 
async io frame
async io frameasync io frame
async io frame
 
异步io框架的实现
异步io框架的实现异步io框架的实现
异步io框架的实现
 
大话redis设计实现
大话redis设计实现大话redis设计实现
大话redis设计实现
 
聊聊我接触的集群管理
聊聊我接触的集群管理聊聊我接触的集群管理
聊聊我接触的集群管理
 
MySQL InnoDB 源码实现分析(一)
MySQL InnoDB 源码实现分析(一)MySQL InnoDB 源码实现分析(一)
MySQL InnoDB 源码实现分析(一)
 

Ähnlich wie python gil

Ähnlich wie python gil (20)

CppConcurrencyInAction - Chapter07
CppConcurrencyInAction - Chapter07CppConcurrencyInAction - Chapter07
CppConcurrencyInAction - Chapter07
 
Mit cilk
Mit cilkMit cilk
Mit cilk
 
Java Core | Understanding the Disruptor: a Beginner's Guide to Hardcore Concu...
Java Core | Understanding the Disruptor: a Beginner's Guide to Hardcore Concu...Java Core | Understanding the Disruptor: a Beginner's Guide to Hardcore Concu...
Java Core | Understanding the Disruptor: a Beginner's Guide to Hardcore Concu...
 
Errors errors, everywhere! - JSession
Errors errors, everywhere! - JSessionErrors errors, everywhere! - JSession
Errors errors, everywhere! - JSession
 
Understanding the Disruptor
Understanding the DisruptorUnderstanding the Disruptor
Understanding the Disruptor
 
PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...
 
COSCUP: Introduction to Julia
COSCUP: Introduction to JuliaCOSCUP: Introduction to Julia
COSCUP: Introduction to Julia
 
A petri-net
A petri-netA petri-net
A petri-net
 
Introduction to julia
Introduction to juliaIntroduction to julia
Introduction to julia
 
2.8A Function Operations
2.8A Function Operations2.8A Function Operations
2.8A Function Operations
 
[Pycon 2015] 오늘 당장 딥러닝 실험하기 제출용
[Pycon 2015] 오늘 당장 딥러닝 실험하기 제출용[Pycon 2015] 오늘 당장 딥러닝 실험하기 제출용
[Pycon 2015] 오늘 당장 딥러닝 실험하기 제출용
 
Python in 90mins
Python in 90minsPython in 90mins
Python in 90mins
 
Lecture03
Lecture03Lecture03
Lecture03
 
Low latency in managed code
Low latency in managed codeLow latency in managed code
Low latency in managed code
 
High Performance Systems Without Tears - Scala Days Berlin 2018
High Performance Systems Without Tears - Scala Days Berlin 2018High Performance Systems Without Tears - Scala Days Berlin 2018
High Performance Systems Without Tears - Scala Days Berlin 2018
 
2020 1학기 정기스터디 1주차
2020 1학기 정기스터디 1주차2020 1학기 정기스터디 1주차
2020 1학기 정기스터디 1주차
 
zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...
zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...
zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
 
20170415 當julia遇上資料科學
20170415 當julia遇上資料科學20170415 當julia遇上資料科學
20170415 當julia遇上資料科學
 
20171127 當julia遇上資料科學
20171127 當julia遇上資料科學20171127 當julia遇上資料科學
20171127 當julia遇上資料科學
 

Mehr von rfyiamcool (9)

Redis cluster那些事儿
Redis cluster那些事儿Redis cluster那些事儿
Redis cluster那些事儿
 
Golang advance
Golang advanceGolang advance
Golang advance
 
Golang 高性能实战
Golang 高性能实战Golang 高性能实战
Golang 高性能实战
 
Mysql fast share
Mysql fast shareMysql fast share
Mysql fast share
 
python高级内存管理
python高级内存管理python高级内存管理
python高级内存管理
 
Micro service
Micro serviceMicro service
Micro service
 
分析mysql acid 设计实现
分析mysql acid 设计实现分析mysql acid 设计实现
分析mysql acid 设计实现
 
Raft
Raft Raft
Raft
 
cdn的那些事儿
cdn的那些事儿cdn的那些事儿
cdn的那些事儿
 

Kürzlich hochgeladen

Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 

Kürzlich hochgeladen (20)

AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 

python gil