这是一个单独的问题,但与我问的上一个问题相关here https://stackoverflow.com/questions/40544480/c-correct-way-to-pause-resume-an-stdthread/40544769?noredirect=1#comment68344743_40544769
我正在使用一个std::thread
in my C++
代码不断轮询一些数据并将其添加到缓冲区。我用一个C++ lambda
像这样启动线程:
StartMyThread() {
thread_running = true;
the_thread = std::thread { [this] {
while(thread_running) {
GetData();
}
}};
}
thread_running
is an atomic<bool>
在类头中声明。这是我的GetData
功能:
GetData() {
//Some heavy logic
}
接下来我还有一个StopMyThread
我设置的函数thread_running
为 false 以便退出 while 循环lambda block
.
StopMyThread() {
thread_running = false;
the_thread.join();
}
据我了解,我可以使用暂停和恢复线程std::condition_variable
正如所指出的here https://stackoverflow.com/questions/40544480/c-correct-way-to-pause-resume-an-stdthread/40544769?noredirect=1#comment68344743_40544769在我之前的问题中。
但是如果我只使用有什么缺点吗std::atomic<bool>
thread_running
执行或不执行其中的逻辑GetData()
像下面这样?
GetData() {
if (thread_running == false)
return;
//Some heavy logic
}
与使用方法相比,这会消耗更多的 CPU 周期吗?std::condition_variable
如上所述 here https://stackoverflow.com/questions/40544480/c-correct-way-to-pause-resume-an-stdthread/40544769?noredirect=1#comment68344743_40544769 ?