~/problems / Locks / Lock (mutex)

Alternate foo and bar

easy ~15 min

FooBar(n) is shared by two threads. Thread A calls foo(print_foo) once, thread B calls bar(print_bar) once. Inside, each method must call its print function exactly n times, and together the output must alternate, starting with foo:

foo bar foo bar ... foo bar      (n pairs)
class FooBar:
    def __init__(self, n: int): ...
    def foo(self, print_foo) -> None: ...   # calls print_foo() n times
    def bar(self, print_bar) -> None: ...   # calls print_bar() n times

Either thread may be started first, and both must return when they're done.

Use threading primitives. No sleeping or busy-waiting.

Example with n = 2: output foo, bar, foo, bar, even when the bar thread starts well before the foo thread.

Show hint

Think of two "turn tokens", one per thread: each thread waits for its own token, prints, then hands the other thread its token. Which token is available at the start?

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

0:00
Ctrl ' run · Ctrl ↵ submit
esc