Leetcode Problem 1115. Print FooBar Alternately

1115. Print FooBar Alternately

Leetcode Solutions

Using Condition Variables and Mutex

  1. Initialize a mutex and two condition variables, one for each function (foo and bar).
  2. In the foo function, acquire the mutex lock.
  3. Print 'foo'.
  4. Signal the condition variable associated with bar and release the mutex lock.
  5. In the bar function, acquire the mutex lock.
  6. Wait on the condition variable until signaled by foo.
  7. Print 'bar'.
  8. Signal the condition variable associated with foo and release the mutex lock.
  9. Repeat steps 2-8 for n iterations.
UML Thumbnail

Using Semaphores

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...