~/problems / Locks / Lock (mutex)

Print in order with locks

easy ~15 min

Three threads share one Order object. One thread calls first, one calls second, one calls third, and they may be started in any order. Whatever the start order, the output must 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

Build it from plain threading.Lock objects stored on the instance (at least two). No sleep and no busy-waiting loops.

Example: if the thread calling third starts first, it blocks until second has printed, which in turn waits for first.

Note: in Python a threading.Lock may be released by a different thread from the one that acquired it. That is a Python quirk: a mutex in C++, Java or pthreads must be unlocked by its owner, so in those languages you would use a semaphore, latch or condition variable for this kind of signalling.

Show hint

A lock that is already held in __init__ works as a "not yet" gate: a thread that tries to acquire it blocks until someone releases it. Which method should release each gate, and which should wait on it?

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

0:00
Ctrl ' run · Ctrl ↵ submit
esc