【发布时间】:2020-05-02 12:05:55
【问题描述】:
我有一个简单的 C++11 线程程序,如下所示。
代码:
#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
int main(int argc, char *argv[]) {
std::cout << "My program starts" << std::endl;
std::atomic<bool> exit_thread(false);
std::thread my_thread = std::thread([&exit_thread]{
do {
std::cout << "Thread is doing something..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
} while (!exit_thread);
});
std::this_thread::sleep_for(std::chrono::seconds(12));
exit_thread = true;
std::cout << "Might have to wait to exit thread" << std::endl;
my_thread.join();
return 0;
}
正如你在上面看到的,有一个循环,它有一个sleep_for,它使线程休眠 5 秒,然后它唤醒并再次循环,前提是exit_thread 设置为 false。主线程等待 12 秒并准备退出,首先将 exit_thread 设置为 true,然后在线程上执行 join。到目前为止一切顺利。
问题:
以上是可以的,适用于客观。 但是存在“潜在问题”。如果线程现在刚刚开始休眠,那么它需要多花 4 秒才能从休眠中发现它现在需要退出。这会延迟退出过程和销毁。
问题:
如何使线程以可中断的方式休眠?这样我就可以通过取消睡眠而不是等待潜在的 4 或 3 或 2 秒来中断睡眠并让线程立即退出。
我认为使用std::condition_variable 可以解决这个问题?大概?我正在寻找一段代码来展示如何。
注意我的代码在 clang 和 gcc 上运行。
【问题讨论】:
-
是的,您需要等待信号量或条件变量超时,而不是无条件休眠。
标签: multithreading c++11 sleep condition-variable stdthread