资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

C++为什么不要在线程中无条件等待

这篇文章主要讲解了“C++为什么不要在线程中无条件等待”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C++为什么不要在线程中无条件等待”吧!

公司主营业务:做网站、网站设计、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。创新互联公司是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。创新互联公司推出平度免费做网站回馈大家。

CP.42:不要无条件等待

Reason(原因)

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 lock(mx);        cv.notify_one();    // wake other thread    }}
void thread2(){    while (true) {        std::unique_lock 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(示例)

templateclass 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 q;};
templatevoid Sync_queue::put(const T& val){    lock_guard lck(mtx);    q.push_back(val);    cond.notify_one();}
templatevoid Sync_queue::get(T& val){    unique_lock 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),它会立刻回到休眠状态继续等待。

Enforcement(实施建议)

Flag all waits without conditions.

标记所有无条件等待。

感谢各位的阅读,以上就是“C++为什么不要在线程中无条件等待”的内容了,经过本文的学习后,相信大家对C++为什么不要在线程中无条件等待这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联,小编将为大家推送更多相关知识点的文章,欢迎关注!


网页名称:C++为什么不要在线程中无条件等待
标题网址:http://cdkjz.cn/article/jcscpd.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220