SlideShare a Scribd company logo
1 of 17
Enhance your Python Code
to go beyond GIL
Nitin Bhojwani
Arabinda Das
Priya Pandian
What is Global
Interpreter
Lock?
The mechanism used by the CPython interpreter
to assure that only one thread executes Python
bytecode at a time.
More about GIL
• Lock at Interpreter Level
• Prevents true parallelism
• Few Exceptions
• Extensions Modules
• No GIL in I/O
• Past Efforts
Positive Side of GIL
• Thread Safe
• Single-threaded Programs
• Easy integration of C libraries
• Simplified Garbage Collection
I/O
75%
Memory
15%
CPU
5%
Other
5%
Percentage
I/O Memory CPU Other
Automation Workloads
How to Solve
• Multithreading
• Multiprocessing
• AsyncIO
• AsyncIO with Multithreading
• AsyncIO with Multiprocessing
Multithreading
• Multiple child threads
• Shared Memory
• But threads waits for GIL
Advantages
• Lesser memory
• Good for Blocking I/O
Multithreading(how)
• Python’s threading module.
• concurrent.futures.ThreadPoolExecutor – abstracts queuing and
distributing tasks to threads.
Multiprocessing
• Multiple child processes
• Message Passing
• Might require more Memory
compared to multi-threading.
Advantages
• No GIL
• Good for CPU bound
Multiprocessing(how)
• Python’s multiprocessing module
• concurrent.futures.ProcessPoolExecutor – abstracts queuing and
distributing tasks to processes.
Caveats of multithreading & multiprocessing
• Context Switches
• No. of Threads/Processes -> No. of Context Switches
• Deciding Optimal number of Threads or Processes
• Varying I/O wait-times
Python AsyncIO
Python AsyncIO(how)
• Python’s asyncio module
• aiohttp - Asynchronous
HTTP Client/Server
for asyncio and Python
Advantages
• No wait (Event Driven)
• Good for non-blocking
AsyncIO with Multithreading/Multiprocessing
Summary
• Multithreading – Blocking I/O
• Multiprocessing – CPU Bound
• AsyncIO – Non-blocking I/O
• AsyncIO with Multithreading – Blocking and Non Blocking I/O
• AsyncIO with Multiprocessing – CPU Bound with Non Blocking I/O
Reach out to Us
• Nitin Bhojwani – nitinbhojwani@outlook.com
• Arabinda Das – darabinda@gmail.com
Thank You!
Q & A

More Related Content

Similar to SRECon19 Asia - Enhance Your Python Code Beyond GIL

Scaling systems for research computing
Scaling systems for research computingScaling systems for research computing
Scaling systems for research computing
The BioTeam Inc.
 
Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Code
rsebbe
 

Similar to SRECon19 Asia - Enhance Your Python Code Beyond GIL (20)

Threads in Operating System | Multithreading | Interprocess Communication
Threads in Operating System | Multithreading | Interprocess CommunicationThreads in Operating System | Multithreading | Interprocess Communication
Threads in Operating System | Multithreading | Interprocess Communication
 
Scaling Systems for Research Computing
Scaling Systems for Research ComputingScaling Systems for Research Computing
Scaling Systems for Research Computing
 
Gpgpu intro
Gpgpu introGpgpu intro
Gpgpu intro
 
Scaling systems for research computing
Scaling systems for research computingScaling systems for research computing
Scaling systems for research computing
 
Gil - the responsible to unable paralellism
Gil - the responsible to unable paralellismGil - the responsible to unable paralellism
Gil - the responsible to unable paralellism
 
Four Python Pains
Four Python PainsFour Python Pains
Four Python Pains
 
Python: Thanks for the memories
Python: Thanks for the memoriesPython: Thanks for the memories
Python: Thanks for the memories
 
Kotlin Multiplatfom In Action
Kotlin Multiplatfom In ActionKotlin Multiplatfom In Action
Kotlin Multiplatfom In Action
 
Advanced python
Advanced pythonAdvanced python
Advanced python
 
Pycon11: Python threads: Dive into GIL!
Pycon11: Python threads: Dive into GIL!Pycon11: Python threads: Dive into GIL!
Pycon11: Python threads: Dive into GIL!
 
Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Code
 
Kotlin Multiplatfom In Action
Kotlin Multiplatfom In ActionKotlin Multiplatfom In Action
Kotlin Multiplatfom In Action
 
Fast Python: Master the Basics to Write Faster Code
Fast Python: Master the Basics to Write Faster CodeFast Python: Master the Basics to Write Faster Code
Fast Python: Master the Basics to Write Faster Code
 
OpenMp
OpenMpOpenMp
OpenMp
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
 
Putting Compilers to Work
Putting Compilers to WorkPutting Compilers to Work
Putting Compilers to Work
 
Python
PythonPython
Python
 
Java in High Frequency Trading
Java in High Frequency TradingJava in High Frequency Trading
Java in High Frequency Trading
 
Takipi
TakipiTakipi
Takipi
 
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
 

Recently uploaded

Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
Kamal Acharya
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
jaanualu31
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
MayuraD1
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

Moment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilMoment Distribution Method For Btech Civil
Moment Distribution Method For Btech Civil
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Wadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxWadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptx
 

SRECon19 Asia - Enhance Your Python Code Beyond GIL

Editor's Notes

  1. Global Interpreter Lock Hint: It’s what the name suggests. Let’s look at the official definition
  2. It’s a lock at Python’s interpreter level that doesn’t allow multiple threads to execute simultaneously, even in different cores of processor. Which means even if you write multi-threaded program, it will keep locking and waiting for data structures. Increases the execution time. However, some extension modules, either standard or third-party, are designed 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 for one thread single-processor case Overcoming this performance issue made the implementation much more complicated and therefore costlier to maintain.
  3. Our code is implicitly thread-safe (as multiple threads can’t run simultaneously on same data) Increased speed of single-threaded programs Easy integration of C libraries that usually are not thread-safe. Simplified Garbage Collection - based on reference counts.
  4. 75% I/0 intensive in general: Call APIs Run commands over SSH Database calls. 15 - 20% Memory intensive Define variables Store arrays and other data structures in memory 5- 10 % CPU intensive Parse request and result If else and other compute logic Think it at Scale of 100 thousands nodes.
  5. We'll look into different approaches to solve the problem while efficiently utilizing our resources.
  6. Spawn multiple threads and use shared memory space to communicate and sync. Lesser memory consumption as memory is shared among child threads. During I/O, GIL is released and other thread can continue with their execution.
  7. Python’s threading module provide all the basic APIs to deal with threads – start, run, join, locking and semaphores etc. It’s seen that Queuing and threading are used together, and so, concurrent.futures has even abstracted queuing of tasks and distributing among threads. It provides ThreadPoolExecutor
  8. Spawning multiple child processes to achieve true parallelism Use message passing for inter-process communication GIL is not even in picture as it’s different processes and different memory space altogether Might require more memory compared to multi-threading
  9. multiprocessing is a package that supports spawning child processes using an API similar to the threading module. Again concurrent.futures has provided an abstraction on queuing of tasks and distributing them among child processes. It provides ProcessPoolExecutor For multiple processes, additional feature here. If we don’t define max_workers, by default, it creates processes equal to number of cores in the machine.
  10. Multiprocessing is a good solution as GIL wait is no longer present. But what about Context Switches ? The Python Interpreter switches between threads to allow concurrency. We want max utilization of system resources but increasing number of threads or processes will increase Context Switching. We’ll need to define right number of threads / processes such that our system resources are maximum utilized. Not all I/O are similar and so wait times will be different for each I/O – considering this it makes it even more difficult.
  11. Event loop is at the core It’s a Single-threaded, single-process design It’s a programming construct A coroutine is a specialized version of a Python generator function. In other words it’s a function that can suspend its execution before reaching return, and it can indirectly pass control to another coroutine for some time.
  12. AsyncIO - Library to write concurrent code using the async/await syntax
  13. File operations (such as logging) can block the event loop: run them in a thread pool. CPU-bound operations will block the event loop: in general it is preferable to run them in a process pool.