Magicsheet logo

Print in Order

Easy
38.4%
Updated 6/1/2025

Asked by 3 Companies

Print in Order

What is this problem about?

The Print in Order concurrency problem asks you to ensure that three methods — first(), second(), third() — are called in order across multiple threads, regardless of the order threads are launched. This easy concurrency coding problem uses synchronization primitives: semaphores, locks, or condition variables. The concurrency interview pattern is demonstrated.

Why is this asked in interviews?

Microsoft, Nvidia, and Google ask this as an introduction to concurrent programming. It tests knowledge of basic synchronization: how to make one thread wait for another to complete. This pattern appears in producer-consumer scenarios, pipeline stages, and sequential task execution.

Algorithmic pattern used

Semaphores (or mutex + condition variables). Initialize two semaphores: sem2 = 0 (second waits for first), sem3 = 0 (third waits for second). first(): run, then signal sem2. second(): wait sem2, run, signal sem3. third(): wait sem3, run.

Example explanation

Threads running in order 3,1,2:

  • Thread 3 (third()): waits on sem3 (value 0).
  • Thread 1 (first()): runs, signals sem2.
  • Thread 2 (second()): sem2 is 1, proceeds, runs, signals sem3.
  • Thread 3 (third()): sem3 is 1, proceeds, runs. Output order: first, second, third always.

Common mistakes candidates make

  • Using locks alone (must pair with condition variables for blocking).
  • Initializing semaphores to 1 instead of 0 (would not block at all).
  • Releasing semaphores before completing the print (wrong ordering).
  • Deadlock from incorrect semaphore initialization or ordering.

Interview preparation tip

Print in Order introduces thread synchronization fundamentals. Semaphores are the cleanest tool: initialize waiting semaphores to 0 so threads block until signaled. Practice this pattern for "barrier synchronization" (all threads wait at a point), "pipeline synchronization" (stage i waits for stage i-1), and "producer-consumer" (producer signals consumer). These are the three core concurrency interview patterns.

Similar Questions