Master the fundamental concepts of cpython internals through this focused micro-challenge.
CPython's GIL is a mutex that lets only one thread execute Python bytecode at a time per process. It simplifies object refcounting but limits CPU-bound parallelism across threads.
The GIL protects CPython's internal structures during concurrent access. Reference count updates, object allocation, and many C API calls assume the GIL is held.
CPU-bound C extensions can release it around long native work:
cLoading…
When the GIL helps versus hurts:
Py_BEGIN_ALLOW_THREADSI/O-bound threads still benefit because blocking syscalls release the GIL while waiting. CPU-bound Python threads on multiple cores, however, mostly take turns holding one lock.
For example, two threads each computing Fibonacci in pure Python rarely achieve 2x throughput; one thread runs bytecode while the other waits.
Extensions that call back into Python API while holding native locks can deadlock with the GIL. Release the GIL before long C work, re-acquire before touching PyObject* unless you know the object is immortal.
This exercise asks you to explain GIL behavior and write a C extension skeleton that releases the lock during heavy work. You will document when threads help (I/O) versus when they do not (CPU-bound Python code).
Write a C program documenting the GIL concept.
Requirements:
Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
All starter code and reference implementations are available for your local setup.
View on Github