Professional Documents
Culture Documents
Understanding The Python GIL: David Beazley
Understanding The Python GIL: David Beazley
Python GIL
David Beazley
http://www.dabeaz.com
Thread 2 run
run run
Thread 3
release acquire release acquire
GIL GIL GIL GIL
Thread 2 READY
• Thread 1 : Running
• Thread 2 : Ready (Waiting for GIL)
Copyright (C) 2010, David Beazley, http://www.dabeaz.com 19
Thread Switching
• Easy case : Thread 1 performs I/O (read/write)
I/O
Running
Thread 1
release
GIL
Thread 2 READY
acquire GIL
cv.signal() dequeues
schedule
Runs later
Thread 2 READY ...
(low priority)
signal signal
Thread
pthreads/OS Context
Switch
schedule
run
Thread 2 READY
sleep
signal Event
run Acquire GIL (fails)
signal
Acquire GIL (fails)
Might repeat
signal
100s-1000s of times
Acquire GIL (fails)
signal
Acquire GIL (success)
run
signal burst
Thread 2 SUSPENDED
By default TIMEOUT
Thread 2 SUSPENDED is 5 milliseconds, but it
can be changed
cv_wait(gil, TIMEOUT)
running
Thread 2 SUSPENDED
cv_wait(gil, TIMEOUT)
TIMEOUT
Thread 2 SUSPENDED
TIMEOUT running
Thread 2 SUSPENDED
TIMEOUT running
Thread 2 SUSPENDED
TIMEOUT running
Thread 2 SUSPENDED
TIMEOUT running
Thread 2 READY
cv_wait(gil, TIMEOUT) cv_wait(gil, TIMEOUT)
data
arrives
TIMEOUT
Thread 2 READY READY
cv_wait(gil, TIMEOUT) cv_wait(gil, TIMEOUT)
data
arrives
running
Thread 3 READY
wakeup
send send
data (executes
(executes
arrives immediately)
immediately)
• That's it!
• Thanks for listening!
• Questions