ProDeveloperTutorial.com

教程和编程解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统编程
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

C ++ 11功能:C ++多线程第10章:C ++线程中的条件变量

前开发者教程 2020年2月26日

条件变量用于阻止和对象直到“notified” to makeup.

要使用条件变量,我们需要使用以下标头:

#include <condition_variable> // std::condition_variable
条件变量在调用其等待函数之一时使用unique_lock锁定线程。
然后,可以通过在相同条件变量上使用notify函数来唤醒该线程。

下面是等待功能

等待: Wait until 已通知
等待:等待超时
等到: Wait until 已通知

以下是通知功能

notify_one:通知一个人可以通知一个线程或所有线程
notify_all:全部通知用于通知所有线程。
什么时候可以使用条件变量?
在以下情况下,我们可以使用它:

假设您有一个余额为0的银行帐户。在这种情况下,如果提款和存款请求同时出现,则提款请求将需要等到存款发生。

在这种情况下,提款可以等待一段时间,并且在存入资金后,可以通知提款线程提款。

现在让我们借助一个示例来理解:

例:

在下面的示例中,我创建了2个方法。 deposit()和withdraw()。

在main()函数中,我们首先调用取款,因为初始余额为0,它将等待直到存款发生。
然后我们调用deposit()函数,它将存入资金。
然后,我们将通知等待线程。
然后将调用withdraw(),并提取金额。

#include <iostream>       // std::cout
#include <chrono>         // std::chrono::milliseconds
#include <thread>         // std::thread
#include <mutex>          // std::timed_mutex
#include <condition_variable>          // std::condition_variable

// for more tutorials 上  C, C ++, DS visit www.ProDeveloperTutorial.com

using namespace std;

std::condition_variable cv;
std::mutex mtx;

int balance = 0;

void deposit(int money)
{
    std::lock_guard<mutex> lg(mtx);

    balance = balance + money;
    cout<<"The current balance is "<<balance<<endl;

    cv.notify_one();

}


void withdraw(int money)
{
    std::unique_lock <mutex> ul(mtx);

    cv.wait(ul, [] {
            return (balance != 0) ? true : false;
    });

   if ( balance >= money)
   {
        balance -= money;
        cout<<"The amount has been withdrawn"<<endl;
   }
   else
   {
        cout<<"The current balance is less than the amount"<<endl;
   }

        cout<<"The current balance is"<<balance<<endl;

}

int main ()
{
    std::thread t1 (withdraw, 400);
    std::thread t2 (deposit, 600);
    
    t1.join();
    t2.join();
    

  return 0;
}

输出:

The current balance is 600
The amount has been withdrawn
The current balance is 200

 

 

该网站上可用的教程列表:

C编程20+章C ++编程80+章
100多个编码问题数据结构和算法85+章
系统设计20+章Shell脚本编写12章
4g LTE 60+章节最常见的编码问题
5G NR 50+章Linux系统编程20+章

 

 

分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性编程问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和编程解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的



<xmp id="hUHKnQk"><map class="AvbiH0R"><colgroup class="dWoheva"></colgroup></map>