← Questions

Run three methods in a fixed order across threads

0
UberCodingLast asked Aug 2025

A coding interview question asked in Uber's coding round, last asked Aug 2025. It tests concurrency, threads and synchronization.

Implement a class with three methods, alpha(), beta() and gamma(). Three different threads call them, one method each, and may start in any order. The output must still be A, B, C, in that order, repeated for N cycles. Use synchronization primitives, not busy waiting, and discuss fairness, deadlocks and performance.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • Printer(n: int) — the number of cycles.
  • alpha(print_a: Callable[[], None]), beta(print_b: Callable[[], None]), gamma(print_c: Callable[[], None]) — each is called once by its own thread and calls its print function n times, so that across all threads the output is ABC repeated n times.

Example

n = 2, threads started in the order gamma, alpha, beta
output  ->  "ABCABC"

n = 1, any start order
output  ->  "ABC"

Constraints

  • 1 <= n <= 10^5.
  • No sleeping or spinning to wait for a turn.

Clarifying questions

  • Is each method called once with a loop inside, or n times by its thread?
  • Which language and which primitives are allowed?
  • What should happen if one thread never starts or dies?
  • Should it be reusable after the n cycles?

What a strong answer covers

  • One shared turn variable guarded by a condition variable: each thread waits until it is its turn, prints, advances the turn and notifies all. Or three semaphores, A starting at 1 and B, C at 0, each thread releasing the next.
  • Why while, not if, around the wait (spurious wakeups and the wrong thread waking).
  • notify_all against notify: with one condition shared by three threads, notify can wake the wrong one and deadlock.
  • Fairness and the cost of a context switch per print; batching is impossible because order is strict.
  • Tests: many runs with random start delays, checking the exact output.

Follow-ups

  • Generalize to k threads printing in a ring.
  • Print numbers 1 to n with one thread for odd and one for even numbers.
  • Add a timeout: if a thread does not take its turn within a second, report an error instead of hanging.

Where it's asked

  • Uber · Coding · Last asked Aug 202560 min · Two rounds; one is often object-oriented design (a parking lot, a meeting scheduler, an expression evaluator) · No AI, except a newer AI-assisted debugging round in some senior loops

What it tests

concurrency · threads · synchronization

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding