boost::condition_variable 設計c++ 生產者消費者隊列


boost::condition_variable 用法:

當線程間的共享數據發生變化的時候,可以通過condition_variable來通知其他的線程。消費者wait 直到生產者通知其狀態發生改變,Condition_variable是使用方法如下:

·當持有鎖之后,線程調用wait

·wait解開持有的互斥鎖(mutex),阻塞本線程,並將自己加入到喚醒隊列中

·當收到通知(notification),該線程從阻塞中恢復,並加入互斥鎖隊列(mutex queue)

 線程被喚醒之后繼續持有鎖運行。

以下一個例子轉自:

http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html

 

template<typename Data>  
class concurrent_queue  
{  
private:  
    std::queue<Data> the_queue;  
    mutable boost::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);  
        return the_queue.empty();  
    }  
    bool try_pop(Data& popped_value)  
    {  
        boost::mutex::scoped_lock lock(the_mutex);  
        if(the_queue.empty())  
        {  
            return false;  
        }  
          
        popped_value=the_queue.front();  
        the_queue.pop();  
        return true;  
    }  
    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();  
    }  
};

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM