liveBook · Manning

Thread safety

As explained in Python Concurrency with asyncio

Thread safety is the property of behaving correctly when accessed or modified concurrently by multiple threads.

Thread safety is the property of behaving correctly when multiple threads or processes access or modify shared data concurrently. An update that looks like one line may contain separate read and write operations, allowing a race condition to produce an unexpected result. section 1.5 section 6.5.1

Practical implications include:

  • Protect shared updates with locks from the threading module to avoid race conditions. section 7.6
  • Use reentrant locks when code may need to acquire the same lock repeatedly, avoiding deadlocks. section 7.6
  • Treat concurrency failures as difficult-to-reproduce bugs because scheduling determines the order of operations. section 6.5.1

A shared counter

Two concurrent workers incrementing a shared value can both read zero, calculate one, and write one, producing a final value of one instead of two. Repeating the test can expose the failure intermittently. section 6.5.1

Figure 1.6 A race condition where two threads try to increment a reference count simultaneously. Instead of an expected count of two, we get one.
01-06

Visualizes two threads incrementing a reference count simultaneously and producing an incorrect count. section 1.5

How Python Concurrency with asyncio covers it

How deep it goes
Explains race conditions through read-modify-write behavior and demonstrates intermittent failures, without detailing atomic-operation rules.
Examples
Demonstrates unsafe shared counters, simultaneous reference-count increments, and CPU-bound Fibonacci work with and without threads.
What you can do after
Apply it by protecting shared updates with locks and recognizing when concurrent code can produce nondeterministic results.
How it connects
Connects thread safety with race conditions, atomicity, locks, deadlocks, shared memory, the GIL, and thread pools.

Also explained in

Compare how 8 books explain thread safety →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.