同步并发操作

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值