Approach Concurrency with Caution
Intuitive Python — by David Muller (23 / 41)
👈 Chapter 3 Ramping Up with Concurrent Code | TOC | Meet Threads and Processes 👉
Running your code concurrently sounds appealing — who doesn’t want to run more code? Unfortunately, running code concurrently can create problems that you didn’t realize even existed. Before diving into concurrency, we’ll start this chapter with a brief forewarning.
One class of problems caused by concurrency are called race conditions. In a classic race condition example, two concurrent banking operations accidentally allow a customer to overdraw his bank account:
- Customer David has $8 in his bank account.
- Process A reads David’s balance of $8.
- Process B reads David’s balance of $8.
- Process A allows David to withdraw $6.
- Process A updates David’s balance to $8 — $6 = $2.
- Process A ends.
- Process B allows David to withdraw $7.
- Process B updates David’s balance to $8 — $7 = $1.
- Process B ends.
Oops! David only has $8, but was able to withdraw a total of $6 + $7 = $13. David’s balance is now $1, but it should be -$5!
Why did the banking software allow David to overdraw his account? The problem occurred at step 3 when process B read David’s balance as $8 without realizing…