Problem Description
Given a class with two methods, foo() and bar(), two threads will call these methods concurrently. Modify the program so that by synchronizing the two threads, the output is "foobar" repeated n times (i.e., every time foo prints "foo" it is immediately followed by bar printing "bar").
Key Insights
- You must enforce the order between the two threads: always printing "foo" before "bar" in each cycle.
- Use synchronization primitives (mutexes, semaphores, condition variables) to alternate the control between the threads.
- The solution typically involves initializing one thread to start (printing "foo") while the other waits until "foo" is printed.
Space and Time Complexity
Time Complexity: O(n) for n iterations. Space Complexity: O(1) additional space aside from synchronization primitives.
Solution
The solution uses synchronization tools (such as semaphores or condition variables) to coordinate the printing between two threads. One thread prints "foo" and then signals the other thread to print "bar". After printing "bar", the second thread signals back to allow the next "foo" to be printed. This alternation continues n times. The key is to ensure the correct order without busy-waiting, and the synchronization primitives used ensure that threads are blocked until they are allowed to proceed.