Junior — Middle
Is it possible to terminate the work of a standard thread started inside its creator thread?
sobes.tech AI
Answer from AI
The standard C++ library does not provide a direct way to forcibly terminate a thread from outside or from within another thread. A thread should finish its work on its own, for example, based on a condition or a flag.
If a thread is started within the thread that created it, the usual ways to terminate the thread are:
- Flags or condition variables: the thread periodically checks the termination flag and exits properly.
- std::thread::join(): the calling thread waits for the child thread to finish.
Example:
#include <thread>
#include <atomic>
#include <iostream>
#include <chrono>
std::atomic<bool> stopFlag(false);
void worker() {
while (!stopFlag.load()) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "Working...\n";
}
std::cout << "Thread is terminating.\n";
}
int main() {
std::thread t(worker);
std::this_thread::sleep_for(std::chrono::seconds(1));
stopFlag.store(true); // signal the thread to finish
t.join();
return 0;
}
Thus, the thread controls its own termination, and the external thread simply signals it.