How to exit all running threads?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
There is usually no safe general “kill all threads now” operation for application code. The normal solution is cooperative shutdown: tell threads to stop, let them check that signal, finish any required cleanup, and then join them.
Use a Shared Stop Signal
A common pattern is a shared flag or event.
This is the right model because the thread exits in a controlled way.
Why Forced Thread Termination Is Dangerous
Threads may hold:
- locks
- file handles
- database transactions
- partially updated shared state
If you terminate them abruptly, you can corrupt program state or leak resources. That is why cooperative shutdown is the standard recommendation instead of trying to stop threads from the outside by force.
Executors and Thread Pools Follow the Same Idea
If you are using an executor or thread pool, the same principle applies. You stop accepting new work, signal shutdown, and wait for existing tasks to finish or observe cancellation.
The exact API varies by language and framework, but the lifecycle model is the same.
Common Pitfalls
- Looking for a universal forced-stop mechanism instead of designing cooperative cancellation.
- Writing worker loops that never check a stop condition.
- Forgetting to join threads after signaling shutdown.
- Holding locks or blocking forever in code that should respond to cancellation.
- Treating thread termination as an error-handling shortcut rather than as part of program design.
Summary
- The usual answer is cooperative shutdown, not forced thread killing.
- Use a shared stop signal that worker threads check regularly.
- Let threads clean up and then join them.
- Design blocking and looping code so it can respond to cancellation.
- Safe thread exit is a coordination problem, not just a single API call.
Related reading
- How to exit all running threads?
- How to exit the entire application from a Python thread?
- How to find an optimum number of processes in GridSearchCV ..., n_jobs ... ?
- How to find what state ManualResetEvent is in?
- How to find what state ManualResetEvent is in?
- How to force Sequential Javascript Execution?
- How to generate async version of wcf functions without service reference?
- How to get async call to return response to main thread, using okhttp?
.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 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.