这篇文章主要讲解了“C++为什么不要在线程中无条件等待”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C++为什么不要在线程中无条件等待”吧!
CP.42:不要无条件等待
A wait without a condition can miss a wakeup or wake up simply to find that there is no work to do.
无条件等待可能错过唤醒,也可能唤醒之后发现无事可做。
Example, bad(反面示例)
std::condition_variable cv;std::mutex mx;void thread1(){ while (true) { // do some work ... std::unique_lock<std::mutex> lock(mx); cv.notify_one(); // wake other thread }}void thread2(){ while (true) { std::unique_lock<std::mutex> lock(mx); cv.wait(lock); // might block forever // do work ... }}
Here, if some other thread consumes thread1's notification, thread2 can wait forever.
这里,如果某个另外的线程消耗了线程1的通知,线程2会永远等待。
Example(示例)
template<typename T>class Sync_queue {public: void put(const T& val); void put(T&& val); void get(T& val);private: mutex mtx; condition_variable cond; // this controls access list<T> q;};template<typename T>void Sync_queue<T>::put(const T& val){ lock_guard<mutex> lck(mtx); q.push_back(val); cond.notify_one();}template<typename T>void Sync_queue<T>::get(T& val){ unique_lock<mutex> lck(mtx); cond.wait(lck, [this] { return !q.empty(); }); // prevent spurious wakeup val = q.front(); q.pop_front();}
Now if the queue is empty when a thread executing get() wakes up (e.g., because another thread has gotten to get() before it), it will immediately go back to sleep, waiting.
现在,当某个线程执行get唤醒时,如果队列为空(例如,由用户另外的线程已经事先执行了get),它会立刻回到休眠状态继续等待。
Flag all waits without conditions.
标记所有无条件等待。
感谢各位的阅读,以上就是“C++为什么不要在线程中无条件等待”的内容了,经过本文的学习后,相信大家对C++为什么不要在线程中无条件等待这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4579737/blog/4382873