Вопрос
Explain what the GIL is, why CPython has it, and what happens at a high level when you run a Python file.
Ответить самому
Сначала сформулируйте ответ как на собеседовании, затем откройте разбор и оцените себя.
Короткий ответ
In CPython, the GIL is a process-level lock that lets only one thread execute Python bytecode at a time. Source is parsed and compiled to bytecode, then the VM interprets bytecode and calls C-implemented runtime functions where relevant.
Полный разбор
The GIL is the Global Interpreter Lock in CPython. It protects interpreter internals, especially reference counting and object memory-management invariants, by allowing only one thread to execute Python bytecode at a time inside a process.
This does not mean threads are useless. Threads can help for I/O-bound work because the thread can release control while waiting on network, disk or other external resources. For CPU-bound Python bytecode, multiple threads do not run Python code in parallel in one CPython process; use multiprocessing, native extensions that release the GIL, vectorized libraries or another runtime when CPU parallelism is needed.
When a Python file is executed, CPython reads source, parses it, compiles it to bytecode, then the bytecode evaluation loop executes instructions. Built-ins and many runtime operations eventually call C implementations, but the user-level Python program is not compiled directly to native machine code in the usual CPython path.
Теория
The interview expected the distinction between Python source, bytecode, interpreter loop and C-level runtime functions.
Типичные ошибки
- Say Python has no compilation at all.
- Say the GIL exists only to prevent user-level race conditions.
- Claim Python threads are never useful.
Как отвечать на собеседовании
- Separate CPU-bound and I/O-bound threading.
- Mention bytecode compilation before interpretation.