stdthread How to wait join for any of the given threads to complete?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
A common concurrency question in C++ is how to wait until any one thread completes, then continue processing. std::thread gives join, but join waits for one specific thread and there is no built-in wait-any primitive for a list of threads. To solve this, you coordinate completion with shared state, condition variables, or futures.
Why join Alone Is Not Enough
std::thread::join is a one-to-one operation. You choose one thread object and block until that thread finishes. If you have ten workers and only need the first result, calling join in a fixed order can block on a slow worker even when a fast worker already completed.
That is why production code usually separates two concerns:
- completion signaling, which tells you that at least one task finished
- thread cleanup, which joins or stops all remaining workers safely
Pattern 1: Signal First Completion with condition_variable
This pattern works with plain std::thread and keeps behavior explicit.
You get wait-any semantics for completion and still correctly join every thread before exit.
Pattern 2: Use Futures for Result-Driven Work
If each worker returns a value, std::future can make completion checks cleaner. You can poll futures with wait_for in a loop and react when one becomes ready.
This pattern is simple for value-producing tasks, but polling intervals should be tuned to avoid unnecessary CPU wakeups.
Cleanup and Cancellation Strategy
Waiting for first completion does not automatically stop other threads. Decide what should happen next:
- allow other workers to finish naturally
- request cancellation with cooperative flags or stop tokens
- keep workers running if they provide ongoing background service
In C++20, std::jthread plus stop_token can simplify cooperative cancellation and reduce cleanup bugs.
Performance and Design Considerations
The right pattern depends on workload. For short tasks, polling futures can be fine. For long tasks with unpredictable completion, event-driven signaling with condition variables is usually more efficient. If you need rich composition semantics, task systems or thread pools may be better than managing many raw thread objects.
Also avoid one thread per tiny task. Oversubscription can hurt performance due to context switching and cache disruption.
Common Pitfalls
A frequent bug is treating the first completed thread as if all work is complete and then exiting without joining others. That can terminate the program while workers still run. Another issue is writing shared completion flags without synchronization, which causes data races and undefined behavior. Polling futures in a tight loop without sleep can also burn CPU unnecessarily. Finally, calling get on a future more than once throws, so store result values immediately if you need to reuse them.
Summary
std::threadhas no built-in wait-any operation across many threads.- Use
condition_variableor futures to signal first completion. - Keep completion signaling separate from thread cleanup and joining.
- Decide explicit behavior for remaining workers after first completion.
- Prefer structured concurrency patterns when thread coordination grows complex.
Related reading
- stdunique_lockstdmutex or stdlock_guardstdmutex?
- stop a thread before closing form
- Stop Parallel.ForEachAsync
- Stopping/Destroying a Thread
- stdtransform and toupper, no matching function
- stdwstring VS stdstring
- Strange async code behavior
- Strategy to keep local cache see the same version of data in a distributed system
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.