PYTHON ADVANCED: PROFESSIONAL ENGINEERING MASTERY / L06THREADING AND THE GIL: CONCURRENT PYTHON
课程 · 12 · 06 / 12
LESSON 06 · ADVANCED · 55 MIN · ◆ 3 INSTRUMENTS

Threading and the GIL: Concurrent Python

Master threading in Python, understand the Global Interpreter Lock, use synchronization primitives, and know when threading helps vs. hurts.

TIP

Learning Objectives: After this lesson, you'll understand threading in Python, the Global Interpreter Lock (GIL) and its implications, synchronization primitives, and when threading helps vs. hurts performance.

Understanding Concurrency vs Parallelism

Before diving into threading, let's clarify these often-confused concepts:

FIG. 02Flow Diagram
INTERACTIVE
LOADING INSTRUMENT
Fig. 02Interactive flow diagrams, timelines, and process visualizations
FIG. 04Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 04Interactive Python code execution environment

Basic Threading

Creating Threads

FIG. 06Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 06Interactive Python code execution environment

Daemon Threads

FIG. 08Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 08Interactive Python code execution environment

The Global Interpreter Lock (GIL)

TIP

🎥 Watch this once and you'll get the GIL forever: David Beazley's Understanding the GIL talk (PyCon 2010). Live demos show exactly why CPU-bound multithreading goes nowhere in CPython, and why I/O-bound code still benefits. 38 minutes; pays back in saved debugging hours.

The GIL is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecode simultaneously.

FIG. 10Flow Diagram
INTERACTIVE
LOADING INSTRUMENT
Fig. 10Interactive flow diagrams, timelines, and process visualizations

Understanding the GIL

FIG. 12Memory Visualizer
INTERACTIVE
LOADING INSTRUMENT
Fig. 12Visual representation of memory layout

Use the memory visualizer above to see how threads share the same memory space. Now let's see the GIL's impact:

FIG. 14Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 14Interactive Python code execution environment

When Threading DOES Help: I/O-Bound Tasks

FIG. 16Flow Diagram
INTERACTIVE
LOADING INSTRUMENT
Fig. 16Interactive flow diagrams, timelines, and process visualizations
FIG. 18Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 18Interactive Python code execution environment

Synchronization Primitives

When multiple threads access shared data, we need synchronization.

FIG. 20Flow Diagram
INTERACTIVE
LOADING INSTRUMENT
Fig. 20Interactive flow diagrams, timelines, and process visualizations

Locks (Mutex)

FIG. 22Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 22Interactive Python code execution environment

RLock (Reentrant Lock)

FIG. 24Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 24Interactive Python code execution environment

Semaphore - Limited Resource Access

FIG. 26Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 26Interactive Python code execution environment

Event - Thread Signaling

FIG. 28Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 28Interactive Python code execution environment

Condition - Complex Coordination

FIG. 30Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 30Interactive Python code execution environment

Thread-Safe Data Structures

FIG. 32Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 32Interactive Python code execution environment

Thread Pooling

FIG. 34Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 34Interactive Python code execution environment

Practice Exercises

Exercise 1: Thread-Safe Cache

FIG. 36Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 36Interactive Python code execution environment

Exercise 2: Worker Pool with Results

FIG. 38Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 38Interactive Python code execution environment

Key Takeaways

ConceptDescription
GILPrevents true parallelism for CPU-bound Python code
ThreadingBest for I/O-bound tasks (network, file, database)
LockMutual exclusion, one thread at a time
RLockReentrant lock, same thread can acquire multiple times
SemaphoreLimit concurrent access to N threads
EventSimple thread signaling
ConditionComplex thread coordination
QueueThread-safe producer-consumer pattern

When to Use Threading

Use CaseThreading Appropriate?
Network requestsYes
File I/OYes
Database queriesYes
CPU calculationsNo (use multiprocessing)
GUI responsivenessYes
Web scrapingYes

Next Steps

In the next lesson, we'll explore Multiprocessing—bypass the GIL with true parallelism, use process pools, manage shared state, and understand inter-process communication.


Ready for true parallelism? Multiprocessing awaits!


Further Reading

The GIL — Required Watching

Official Docs

Tutorials

When Threading Wins (and When It Doesn't)

  • CPU-bound → Threading is mostly useless under the GIL. Use multiprocessing or write the hot path in C/Rust/numpy.
  • I/O-bound → Threading works, but asyncio is usually cleaner for hundreds-to-thousands of concurrent operations.
  • Mixedconcurrent.futures.ThreadPoolExecutor for compatibility with sync libraries.

Books

  • Book: Fluent Python (2nd ed.) — Chapter 19 ("Concurrency Models in Python") — best single-chapter overview anywhere.
  • Book: Python Concurrency with asyncio — Matthew Fowler. Covers the threading/asyncio boundary well.