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