Approach Concurrency with Caution

Intuitive Python — by David Muller (23 / 41)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 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:

  1. Customer David has $8 in his bank account.
  2. Process A reads David’s balance of $8.
  3. Process B reads David’s balance of $8.
  4. Process A allows David to withdraw $6.
  5. Process A updates David’s balance to $8 — $6 = $2.
  6. Process A ends.
  7. Process B allows David to withdraw $7.
  8. Process B updates David’s balance to $8 — $7 = $1.
  9. 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…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.