Bitpath

Lesson 2 · Unit 02

Locks

One thread at a time through the critical section

12 exercisesabout 3 min

What you practise

  • Critical sections, a mutex with with lock:, holding it for as little as possible, atomic operations, why a lock around the wrong region fixes nothing

Try a question from this lesson

Pick one

Two threads lose updates because their read, add and write steps interleave. Which rule would make the result correct every time?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

A lock

A lock has one holder at a time. with lock: takes it, runs the block, and releases it, even if the block raises an error.

A second thread reaching with lock: waits until the first is out.

The code inside is the critical section: the steps that must not interleave.

Python
import threading

lock = threading.Lock()
counter = 0

def add():
    global counter
    with lock:          # one at a time
        counter += 1    # critical section

Concept

Small and complete

A critical section should be complete: the whole read-modify-write, or the whole check-and-act, in one block.

It should also be small: only the lines that touch shared data. Slow work (network, disk, heavy computing) stays outside.

Too little inside the lock brings the race back. Too much makes every other thread wait.

9 more exercises in the app

  • 1× type the answer
  • 1× fill the blanks
  • 4× multiple choice
  • 2× true or false
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy