Knowledge Guide
HomeConcurrencyConcurrency Problems

Problem 13 Synchronization of Dual Threads

Overview

The "Synchronization of Dual Threads" problem is a classic demonstration of concurrent thread management. Given two threads, A and B, with the responsibilities of printing "foo" and "bar" respectively, the task is to ensure a synchronized output of "foobar" repetitively for a given 'n' times. This problem emphasizes the significance of thread synchronization in producing consistent and predictable results in concurrent systems.

Pseudocode

Initialize a semaphore or mutex called fooLock with a value of 1 Initialize a semaphore or mutex called barLock with a value of 0 Function printFoo(): for i from 1 to n do: Acquire fooLock Print "foo" Release barLock Function printBar(): for i from 1 to n do: Acquire barLock Print "bar" Release fooLock Main: Start Thread A -> Target: printFoo Start Thread B -> Target: printBar

Explanation

  1. We start by defining a FooBar class that has methods foo and bar to print "foo" and "bar" respectively.
  2. The synchronization is achieved using a mutex mtx and two condition variables fooPrinted and barPrinted.
  3. In the foo method, we ensure that "foo" is printed first. Once printed, it sets fooDone to true and signals the barPrinted condition variable to allow the bar method to print "bar".
  4. The bar method waits for fooDone to be true. Once "bar" is printed, it resets fooDone to false and signals the fooPrinted condition variable to allow the next iteration.
  5. In the main function, we create two threads, threadFoo and threadBar, to execute the foo and bar methods respectively.
  6. The pthread_join function ensures the main thread waits for both threads to finish their execution.

Algorithm Walkthrough

Let’s emphasize synchronization aspects in the walkthrough to help understand how the program ensures proper ordering of "foo" and "bar" printing.

Initial Setup

Starting Threads

Walkthrough of Loop Iterations with Synchronization Focus:

Iteration 1

Iterations 2 to 5

Joining Threads

Final Result

Flow Chart
Flow Chart
java
public class Solution {

  private int n;
  private boolean fooTurn = true; // Flag to determine which thread should run

  public Solution(int n) {
    this.n = n;
  }

  public synchronized void foo(Runnable printFoo) throws InterruptedException {
    for (int i = 0; i < n; i++) {
      // Wait while it's not foo's turn
      while (!fooTurn) {
        wait();
      }

      // printFoo.run() outputs "foo"
      printFoo.run();

      fooTurn = false; // Make it bar's turn
      notify(); // Notify other thread to wake up
    }
  }

  public synchronized void bar(Runnable printBar) throws InterruptedException {
    for (int i = 0; i < n; i++) {
      // Wait while it's not bar's turn
      while (fooTurn) {
        wait();
      }

      // printBar.run() outputs "bar"
      printBar.run();

      fooTurn = true; // Make it foo's turn
      notify(); // Notify other thread to wake up
    }
  }

  public static void main(String[] args) {
    Solution foobar = new Solution(5);

    // Threads to execute the foo and bar methods in parallel
    Thread thread1 = new Thread(() -> {
      try {
        foobar.foo(() -> System.out.print("foo"));
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    });

    Thread thread2 = new Thread(() -> {
      try {
        foobar.bar(() -> System.out.print("bar"));
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    });

    // Start both threads
    thread1.start();
    thread2.start();
  }
}
🤖 Don't fully get this? Learn it with Claude

Stuck on Problem 13 Synchronization of Dual Threads? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🪜 Hint ladder (no spoilers)

Progressively stronger hints — you still solve it.

I'm working on the problem **Problem 13 Synchronization of Dual Threads** (Concurrency). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🎨 Explain the approach visually

See the technique, not just code.

Explain the optimal approach to **Problem 13 Synchronization of Dual Threads** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔍 Review my solution

Catch bugs, edge cases, sub-optimality.

I'll paste my solution to **Problem 13 Synchronization of Dual Threads**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔁 Drill the pattern

Lock in recognition with look-alikes.

Give me 2 problems that use the SAME underlying pattern as **Problem 13 Synchronization of Dual Threads**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes