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.
Visualizes two threads incrementing a reference count simultaneously and producing an incorrect count. section 1.5







