How to force a thread terminate in CPP
时间: 2023-09-20 14:02:58 浏览: 49
In C++, you can force a thread to terminate by calling the `std::thread::terminate()` function. However, this function is not recommended to use because it can cause various problems like resource leaks and undefined behavior.
A better way to terminate a thread is to use a flag variable that is checked periodically by the thread. When the flag variable is set, the thread should gracefully exit. Here's an example:
```
#include <thread>
#include <atomic>
std::atomic<bool> stop_flag(false);
void thread_function()
{
while (!stop_flag)
{
// Do some work
}
}
int main()
{
std::thread t(thread_function);
// Set the stop flag after some time
std::this_thread::sleep_for(std::chrono::seconds(5));
stop_flag = true;
t.join(); // Wait for the thread to exit
return 0;
}
```
In this example, the `thread_function()` checks the `stop_flag` variable periodically, and when it is set to `true`, the thread exits gracefully. The `main()` function sets the `stop_flag` after some time and waits for the thread to exit using the `std::thread::join()` function.