同步并发操作

独立线程上同步操作: 条件变量(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

  1. acquire a std::mutex (typically via std::lock_guard)
  2. perform the modification while the lock is held
  3. 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

  1. acquire a std::unique_lock<std::mutex>, on the same mutex as used to protect the shared variable
  2. either
  1. check the condition, in case it was already updated and notified
  2. execute waitwait_for, or wait_until. The wait operations atomically release the mutex and suspend the execution of the thread.
  3. 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

  1. use the predicated overload of waitwait_for, and wait_until, which takes care of the three steps above

std::condition_variable works only with std::unique_lock<std::mutex>;

上一篇:昨天学习了一些tensorflow入门知识,经历各种奇葩错误,现在奉献一份安装tensorflow2就可以跑的demo


下一篇:TCPDUMP捕获SQL