独立线程上同步操作: 条件变量(condition variables)+期值(future) --> 等待事件。
误差不敏感的选择: 等待方法:std::this_thread::sleep_for(std::chrono::milliseconds(100)) //休眠100毫秒
问题:休眠时间是个学问。
最优选择,使用条件变量等待条件。
c++提供2个: std::condition_variable(plus std::mutex) + std::condition_variable_any(plus 类似mutex的最低标准的任何东西)
std::condition_variable (since C++11)
notify_one: notifies one waiting thread
notify_all : notifies all waiting threads
wait: blocks the current thread until the condition variable is woken up
wait_for: blocks the current thread until the condition variable is woken up or after the specified timeout duration
wait_until: blocks the current thread until the condition variable is woken up or until specified time point has been reached
The thread that intends to modify the shared variable has to
- acquire a
std::mutex
(typically via std::lock_guard) - perform the modification while the lock is held
- execute notify_one or notify_all on the
std::condition_variable
(the lock does not need to be held for notification)
Any thread that intends to wait on std::condition_variable
has to
- acquire a std::unique_lock<std::mutex>, on the same mutex as used to protect the shared variable
- either
- check the condition, in case it was already updated and notified
- execute wait, wait_for, or wait_until. The wait operations atomically release the mutex and suspend the execution of the thread.
- When the condition variable is notified, a timeout expires, or a spurious wakeup occurs, the thread is awakened, and the mutex is atomically reacquired. The thread should then check the condition and resume waiting if the wake up was spurious.
or
- use the predicated overload of wait, wait_for, and wait_until, which takes care of the three steps above
std::condition_variable
works only with std::unique_lock<std::mutex>;