如何暂停或以其他方式阻止线程,然后在发生特定情况时恢复它?
换句话说..我有一个与微控制器通信的键盘。当按下一个键时,控制器会在一个引脚上抛出一个硬件中断(你会明白你什么时候会看到代码),它对应一个布尔值。
bool condition = this->MCP23017->readPin(this->INTERRUPT_KB) == this->MCP23017->PIN_LOW
我需要一些暂停线程的东西(是的,那个条件在一个被std :: thread对象调用的方法内),条件仍为false,并在它为真时重新激活它。
如果我在变量周围放置一个循环,则CPU会达到100%,这会浪费很多功率,因为线程处于活动等待状态。我需要比这更有效的东西。
答案 0 :(得分:1)
使用std::condition_variable
使用 wait / notify 无限期暂停线程,直到满足条件并通知线程。
std::mutex m;
std::condition_variable cond;
std::atomic_bool condition_flag{false}; // Used as condition in this example.
// Create a new thread of execution.
std::thread t{[&] {
{
std::unique_lock<std::mutex> lock{m}; // Aquire lock on mutex.
/* Wait until notified. Lock is released while waiting.
When notified; first check if condition is satisfied.
If not then resume waiting. */
cond.wait(lock, [&] { return condition_flag.load(); });
} // Release lock on mutex.
/* Resume thread execution. */
}};
/* Do something else in original thread before notifying. */
condition_flag = true; // Atomically satisfy condition.
cond.notify_all(); // Notify all threads waiting on 'cond' to reevaluate condition.
t.join(); // Wait for thread to finish execution.