ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

同步并发操作

2021-02-19 21:29:16  阅读:196  来源: 互联网

标签:std 同步 thread 并发 mutex variable 操作 condition wait


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

标签:std,同步,thread,并发,mutex,variable,操作,condition,wait
来源: https://blog.csdn.net/qiuyoujie/article/details/113869973

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有