02C++條件變量

1. 條件變量

​ 多線程編程中,等待由另外一個線程觸發一個時間的最基本機制是條件變量。從概念上說,條件變量與某些事件或其餘條件相關,並且一個或多個線程能夠等待該條件被知足。當某個線程已經肯定條件獲得知足,它就能夠通知一個或多個正在條件變量上進行等待的線程,以便喚醒它們並讓它們繼續處理。ios

#pragma once
#pragma execution_character_set("utf-8")
#include <iostream>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <list>

using namespace std;

//下面的例子,一個條件變量值用於控制兩個線程運行的前後順序。
//getData線程wait中先阻塞條件變量,等到putData線程中發送通知時,wait解除阻塞,向下運行。
std::mutex mut;
std::condition_variable data_cond;
std::list<int> data_list;

const int g_count = 11;

void putData()
{
    for (int i = 0; i < g_count; ++i)
    {
        std::this_thread::sleep_for(std::chrono::seconds(2));
        int data = i * 1000;
        std::lock_guard<std::mutex> lk(mut);
        //添加數據
        data_list.push_back(data);
        cout << "putData():" << data << endl;
        data_cond.notify_all();
    }
}

void getData(const string threadName)
{
    while (true)
    {
        std::unique_lock<std::mutex> lk(mut);
        //更直接與直觀的寫法(當while條件爲true時阻塞)
        while (data_list.empty())
        {
            data_cond.wait(lk);
        }
        //wait中的第二個表達式參數返回true時,解除阻塞。
//      data_cond.wait(
//          lk, [](){ return !data_list.empty(); });
        int data = data_list.front();
        data_list.pop_front();
        lk.unlock();
        //處理數據
        cout << threadName << " getData():" << data << endl;
        if (data > 10000)
        {
            break;
        }
    }
    
}

int main()
{
    thread t1(putData);
    thread t2(getData, "Rock");


    t1.join();
    t2.join();

    return 0;
}

運行結果以下:編程

putData():0
Rock getData():0
putData():1000
Rock getData():1000
putData():2000
Rock getData():2000
putData():3000
Rock getData():3000
putData():4000
Rock getData():4000
putData():5000
Rock getData():5000
putData():6000
Rock getData():6000
putData():7000
Rock getData():7000
putData():8000
Rock getData():8000
putData():9000
Rock getData():9000
putData():10000
Rock getData():10000
相關文章
相關標籤/搜索