Releasing GIL in C extension:
Give a C extension code and one needs to concurrently execute it with other threads in the Python interpreter. For this Global Interpreter Lock (GIL) has to be released and reacquired.
Code #1 : Releasing and Reacquiring GIL by inserting following macros
Mixing Threads from C and Python:
Considering a situation, that a given program involves a mix of C, Python and threads. But some of the given threads are created from C outside the control of the Python interpreter and also certain threads utilize functions in the Python C API.
What’s solution then?
If there is a mix of Python, C and threads, proper initialization and management of Python’s Global Interpreter Lock (GIL) is important. Given code below explains the situation, their code can be used anywhere (prior to the creation of threads) in the C program.
Code #2 :
For any C involving Python objects or the Python C API, GIL needs to be acquired and released first. This can be performed using
PyGILState_Release() as in the code given below. Every call to
PyGILState_Ensure() must have a matching call to
Code #3 :
It is not so easy to have so much things going at once, involving a mix of a Python code, C code and their threads. To perform so, it is to be taken care that the interpreter is properly initialized and that C code involving the interpreter has the proper GIL management calls, it all should work.
PyGILState_Ensure() call does not immediately preempt or interrupt the interpreter. If other code is currently executing, this function will block until that code decides to release the Global Interpreter Lock (GIL).
- What is the Python Global Interpreter Lock (GIL)
- Python VLC MediaPlayer - Releasing Object
- PyQt5 QCalendarWidget - Releasing Grabbed Keyboard input
- PyQt5 QCalendarWidget - Releasing Grabbed Mouse Input
- MoviePy – Releasing Video File Clip
- Python | Communicating Between Threads | Set-1
- Python | Communicating Between Threads | Set-2
- Joining Threads in Python
- Important differences between Python 2.x and Python 3.x with examples
- Creating and updating PowerPoint Presentations in Python using python - pptx
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
- Python | Merge Python key values to list
- Reading Python File-Like Objects from C | Python
- Python | Add Logging to a Python Script
- Python | Add Logging to Python Libraries
- Python | Visualizing O(n) using Python
- Python | Index of Non-Zero elements in Python list
- Python | Convert list to Python array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.