C++中如何退出正在sleep的线程
时间: 2024-04-30 11:03:20 浏览: 11
在C++中,线程的退出通常是通过设置一个标志或者变量来控制。一种方法是使用std::atomic_bool来控制线程是否应该继续运行。在主线程中设置该变量为false,然后在需要退出线程时,线程将检查该变量的值,并在下一个循环迭代中退出。
另外,如果线程正在休眠,可以使用std::condition_variable来唤醒线程并退出。在主线程中设置一个退出标志,并调用notify_one()函数来唤醒线程。在线程函数中,使用wait()函数来等待条件变量的通知,并在收到通知时退出线程。下面是一个例子:
```c++
#include <thread>
#include <condition_variable>
#include <atomic>
std::atomic_bool should_exit(false);
std::mutex mutex;
std::condition_variable cv;
void thread_func()
{
while (!should_exit)
{
// do some work
std::unique_lock<std::mutex> lock(mutex);
cv.wait_for(lock, std::chrono::seconds(1));
}
}
int main()
{
std::thread t(thread_func);
// do some work
should_exit = true;
cv.notify_one();
t.join();
return 0;
}
```
在这个例子中,线程函数会在每个循环迭代中等待条件变量的通知。当主线程设置should_exit为true时,它会调用notify_one()通知线程。线程将在下一次循环迭代中检查should_exit的值并退出。