【发布时间】:2018-10-02 14:43:49
【问题描述】:
我正在使用 C++11,我有一个 std::thread,它是一个类成员,它每 2 分钟向听众发送一次信息。其他的,它只是睡觉。所以,我让它休眠 2 分钟,然后发送所需的信息,然后再次休眠 2 分钟。
// MyClass.hpp
class MyClass {
~MyClass();
RunMyThread();
private:
std::thread my_thread;
std::atomic<bool> m_running;
}
MyClass::RunMyThread() {
my_thread = std::thread { [this, m_running] {
m_running = true;
while(m_running) {
std::this_thread::sleep_for(std::chrono::minutes(2));
SendStatusInfo(some_info);
}
}};
}
// Destructor
~MyClass::MyClass() {
m_running = false; // this wont work as the thread is sleeping. How to exit thread here?
}
问题:
这种方法的问题是我无法在线程睡眠时退出线程。我从阅读中了解到,我可以使用std::condition_variable 唤醒它并优雅地退出?但我正在努力寻找一个 simple example 来满足上述情况的要求。我发现的所有condition_variable 示例对于我在这里尝试做的事情来说看起来都太复杂了。
问题:
如何使用std::condition_variable 唤醒线程并在其休眠时优雅退出?或者有没有其他方法可以在没有condition_variable 技术的情况下达到同样的效果?
另外,我发现我需要将std::mutex 与std::condition_variable 结合使用?这真的有必要吗?是不是只在代码中需要的地方添加std::condition_variable逻辑就不能达到目的?
环境:
带有编译器 gcc 和 clang 的 Linux 和 Unix。
【问题讨论】:
-
请注意,您显示的代码充满了语法错误。
-
您在 Windows 上吗?那里有一些操作系统原语可以帮助您。
-
作为
std::condition_variable的替代品 - 对于这种需要一次性信号的情况,您可以使用std::promise<void>和std::future::wait_for() -
@PaulSanders 我的代码需要在 linux 和 unix 上运行。我用开发环境的详细信息更新了问题
-
@FrançoisAndrieux 是的。我正在处理那部分。因为这个问题的重点并不是真正的主题,所以我没有关注那个。无论如何,感谢您添加这一点
标签: c++ c++11 mutex condition-variable stdthread