CUtilityCode

(1) 基於boost的生產者/消費者隊列blog

template<typenameData>
classconcurrent_queue   

{   

private:  
 
    std::queue<Data> the_queue;  
 
    mutableboost::mutex the_mutex;   

    boost::condition_variable the_condition_variable;  
 
public:  
 
    void push(Data const& data)  
 
    {  
 
        boost::mutex::scoped_lock lock(the_mutex);  
 
        the_queue.push(data);  
 
        lock.unlock();  
 
        the_condition_variable.notify_one();  
 
    }  
 
    bool empty() const  
 
    {  
 
        boost::mutex::scoped_lock lock(the_mutex);  
 
        returnthe_queue.empty();   

    }  
 
    bool try_pop(Data& popped_value)   

    {  
 
        boost::mutex::scoped_lock lock(the_mutex);  
 
        if(the_queue.empty())  
 
        {  
 
            returnfalse;  
 
        }  
 
            
 
        popped_value=the_queue.front();  
 
        the_queue.pop();  
 
        returntrue;  
 
    }  
 
    void wait_and_pop(Data& popped_value)
    {  
 
        boost::mutex::scoped_lock lock(the_mutex);  
 
        while(the_queue.empty())  
 
        {  
 
            the_condition_variable.wait(lock);  
 
        }  
 
            
 
        popped_value=the_queue.front();  
 
        the_queue.pop();  
 
    }  
 
};
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息