progress

~/problems / Locks / Lock (mutex)

Print in order with locks

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

Three threads share one Order object, calling first, second and third, started in any order. The output must always be first, second, third.

class Order:
    def first(self, print_first): ...    # must call print_first() exactly once
    def second(self, print_second): ...  # must call print_second() exactly once
    def third(self, print_third): ...    # must call print_third() exactly once

Use plain threading.Lock objects on the instance (at least two). No sleep, no busy-waiting. If third starts first, it blocks until second has printed, which waits for first.

Note: Python lets one thread release a Lock another acquired. In C++, Java or pthreads a mutex must be unlocked by its owner, so you'd signal with a semaphore, latch or condition variable instead.

Show hint

a lock already held in __init__ is a "not yet" gate: acquiring it blocks until someone releases it. Which method releases each gate, and which waits on it?

Topic: Lock (mutex). One thread in a critical section at a time.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc