Run three methods in a fixed order across threads
I was asked this
No reports yet. Sign in to say where you were asked it.
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 functionntimes, so that across all threads the output isABCrepeatedntimes.
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
ntimes 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
ncycles?
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,
Astarting at 1 andB,Cat 0, each thread releasing the next. - Why
while, notif, around the wait (spurious wakeups and the wrong thread waking). -
notify_allagainstnotify: with one condition shared by three threads,notifycan 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
kthreads printing in a ring. - Print numbers 1 to
nwith 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
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
