程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> Boost條件變量condition_variable_any,conditionvariable

Boost條件變量condition_variable_any,conditionvariable

編輯:C++入門知識

Boost條件變量condition_variable_any,conditionvariable


  Boost條件變量可以用來實現線程同步,它必須與互斥量配合使用。使用條件變量實現生產者消費者的簡單例子如下,需要注意的是cond_put.wait(lock)是在等待條件滿足。如果條件不滿足,則釋放鎖,將線程置為waiting狀態,繼續等待;如果條件滿足,則重新獲取鎖,然後結束wait,繼續向下執行。

#include "stdafx.h"
#include <stack>
#include <boost/bind/bind.hpp>
#include <boost/thread.hpp>
#include <boost/thread/lock_factories.hpp>
using namespace std;
class Buffer
{
private:
    boost::mutex mu;

    boost::condition_variable_any cond_put;
    boost::condition_variable_any cond_get;
    int un_read, capacity;

    std::stack<int> m_stk;
    bool isFull()
    {
        return un_read == capacity;
    }
    bool isEmpty()
    {
        return un_read == 0;
    }
public:
    Buffer(size_t n):un_read(0), capacity(n) {}

    void put(int x)
    {
        {
            auto lock = make_unique_lock(mu);
            for (; isFull(); )
            {
                cout << "Full waiting"<<endl;
                cond_put.wait(lock);
            }
            m_stk.push(x);
            ++un_read;
        }
        cond_get.notify_one();
    }

    void get(int *x)
    {
        {
            auto lock = make_unique_lock(mu);
            for (; isEmpty(); )
            {
                cout<<"Empty waiting..."<<endl;
                cond_get.wait(lock);
            }
            --un_read;
            *x = m_stk.top();
            m_stk.pop();
        }
        cond_put.notify_one;
    }

};

Buffer buf(5);
void Producer(int n)
{
    for (int i=0; i<n; i++)
    {
        cout<< "Putting "<<i<<endl;
        buf.put(i);
    }
}

void Consumer(int n)
{
    int x;
    for (int i=0; i<n; i++)
    {
        buf.get(&x);
        cout<<"Getting "<<x<<endl;
    }
}

int main()
{
    boost::thread_group tg;
    tg.create_thread(bind(Producer, 20));

    tg.create_thread(bind(Consumer, 10));
    tg.create_thread(bind(Consumer, 10));

    tg.join_all();

    return 0;
}

  

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved