BlockingQueue.cpp 文件代码

/*
 * BlockingQueue.cpp
 *
 *  Created on: Apr 19, 2013
 *      Author: archy_yu
 */
 
#include "BlockingQueue.h"
 
BlockingQueue::BlockingQueue()
{
    pthread_mutex_init(&this->_mutex,NULL);
    pthread_cond_init(&this->_cond,NULL);
}
 
BlockingQueue::~BlockingQueue()
{
    pthread_mutex_destroy(&this->_mutex);
    pthread_cond_destroy(&this->_cond);
}
 
int BlockingQueue::peek(CommonItem &item)
{
 
    if( !this->_read_queue.empty() )
    {
        item = this->_read_queue.front();
        this->_read_queue.pop();
    }
    else
    {
        pthread_mutex_lock(&this->_mutex);
 
        while(this->_write_queue.empty())
        {
            pthread_cond_wait(&this->_cond,&this->_mutex);
        }
 
        while(!this->_write_queue.empty())
        {
            this->_read_queue.push(this->_write_queue.front());
            this->_write_queue.pop();
        }
 
        pthread_mutex_unlock(&this->_mutex);
    }
 
 
    return 0;
}
 
int BlockingQueue::append(CommonItem item)
{
    pthread_mutex_lock(&this->_mutex);
    this->_write_queue.push(item);
    pthread_cond_signal(&this->_cond);
    pthread_mutex_unlock(&this->_mutex);
    return 0;
}