linuxの下でc++は簡単な生産者消費者キューモデルを実現する


引用する
生産者消費者は古典的なモデルです
生産者、消費者、バッファを利用して、生産者と消費者の結合度を低減します.
生産者と消費者の修正が容易である
以下に記録するのは古典的な単一生産者のマルチ消費者のモデルである.
せっけい構想
キューをバッファとして製品のFIFOを実現
生産者はバッファのpush関数を呼び出し、製品をバッファに追加する
消費者はバッファのpop関数を呼び出し,製品をバッファから取り出す
生産者と消費者は別のスレッドに属しているので、ロックを設定します
クラスの宣言
class CacheQueue
{
    private:
        /**
         * @brief     
         */
        queue<int>* _requests;

        /**
         * @brief    
         **/
        pthread_mutex_t _mutex;

        /**
         * @brief Queue not full conditional object
         **/
        pthread_cond_t _not_full_cond;

        /**
         * @brief Queue not empty conditional object
         **/
        pthread_cond_t _not_empty_cond;

        uint32_t _bufSize;
        
    public:
    
        ChacheQueue();

        void SetMaxLength(uint32_t bufSize);
        /**
          * @brief        
          * @param [in] req:       
          **/
        void Push(int req);

        /**
          * @brief           
          * @param [return] :          
          **/
        int Pop(uint32_t timeout);

        /**
          * @brief     
          **/
        ~CacheQueue();
};

重要な関数はPushとPopであり,生産者はPushを呼び出してバッファに製品を追加し,消費者はPop関数を呼び出して製品を取得する.
スレッド条件_not_full_condはキューが不満で、製品を追加できます.
スレッド条件_not_empty_condはキューが空でなく、製品を取得できることを示します.
Push関数
void CacheQueue::Push(int req)
{
	/**
	*   
	*/
    pthread_mutex_lock(&_mutex);
	
	/**
	*      ,    
	*/
    while (_requests->size() == _bufSize)
    {
        pthread_cond_wait(&_not_full_cond, &_mutex);
    }
    _requests->push(req);
	
	/**
	*       
	*/
    pthread_cond_signal(&_not_empty_cond);

	/**
	*   
	*/
    pthread_mutex_unlock(&_mutex);
}

Pop関数
int CacheQueue::Pop(uint32_t timeout)
{
    int ret = 0;
    int req = NO_DATA;
	/**
	*   
	*/
    pthread_mutex_lock(&_mutex);
	/**
	*           
	*/
    struct timeval now;
	struct timespec timepass;
	gettimeofday(&now, NULL);
	timepass.tv_sec = now.tv_sec + timeout;
	timepass.tv_nsec = 0;
    while (ret == 0 && _requests->empty())
    {
		ret = pthread_cond_timedwait(&_not_empty_cond, &_mutex, &timepass);
    }
	/**
	*     ,        
	*/
    if(ret!=0)
    {
        pthread_mutex_unlock(&_mutex);
        return req;
    }
	/**
	*     ,        
	*/
    req = _requests->front();
    _requests->pop();
    pthread_cond_signal(&_not_full_cond);
	/**
	*   
	*/
    pthread_mutex_unlock(&_mutex);
    return req;
}