c++11新特性之條件變量

std::condition_variable 是爲了解決死鎖而生的。當互斥操作不夠用而引入的。比如,線程可能需要等待某個條件爲真才能繼續執行,而一個忙等待循環中可能會導致所有其他線程都無法進入臨界區使得條件爲真時,就會發生死鎖。所以,condition_variable實例被創建出現主要就是用於喚醒等待線程從而避免死鎖。std::condition_variable的 notify_one()用於喚醒一個線程;notify_all() 則是通知所有線程。
C++11中的std::condition_variable就像Linux下使用pthread_cond_wait和pthread_cond_signal一樣,可以讓線程休眠,直到別喚醒,現在在從新執行。線程等待在多線程編程中使用非常頻繁,經常需要等待一些異步執行的條件的返回結果。

#include <mutex>
#include <condition_variable>
#include <thread>

mutex g_mtx;
condition_variable g_cv;
int  g_bReady = false;

void print_id(int id) 
{
    unique_lock<mutex> lck(g_mtx);
    while (!g_bReady)
    {
        g_cv.wait(lck);
    }
    std::cout << "thread " << id << '\n';

}

void go()
{
    unique_lock<mutex> lck(g_mtx);
    g_bReady = true;
    g_cv.notify_all();
}
int main(int argc, char** argv)
{
    thread threads[8];
    for (int i = 0; i < 8; ++i)
    {
        threads[i] = thread(print_id, i);
    }

    cout << "8 threads ready to race...\n";
    go();
    for (auto& th : threads) th.join();

    return 0;
}

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章