线程安全通用缓冲区队列类

来源:互联网 发布:网络机顶盒哪个牌子的好 编辑:程序博客网 时间:2024/04/28 02:16
// 通用库namespace Common{namespace Thread{// 线程安全通用缓冲区队列template <typename Type>class CThreadBuffer{public:CThreadBuffer(){pthread_mutex_init(&m_lock, NULL);pthread_cond_init(&m_notEmpty, NULL);pthread_cond_init(&m_notFull, NULL);m_iReadPos = 0;m_iWritePos = 0;}~CThreadBuffer(){pthread_mutex_destroy(&m_lock);pthread_cond_destroy(&m_notEmpty);pthread_cond_destroy(&m_notFull);}public:// 入队void Push(const Type& data){pthread_mutex_lock(&m_lock);// 等待缓冲区未满if ((m_iWritePos + 1) % BUFF_SIZE == m_iReadPos){pthread_cond_wait(&m_notFull, &m_lock);}// 写数据,并移动指针m_buffer[m_iWritePos] = data;m_iWritePos++;if (m_iWritePos >= BUFF_SIZE){m_iWritePos = 0;}// 设置缓冲区非空的条件变量pthread_cond_signal(&m_notEmpty);pthread_mutex_unlock(&m_lock);}// 出队void Pop(Type& data){pthread_mutex_lock(&m_lock);// 等待缓冲区非空if (m_iWritePos == m_iReadPos){pthread_cond_wait(&m_notEmpty, &m_lock);}// 读数据,移动读指针data = m_buffer[m_iReadPos];m_iReadPos++;if (m_iReadPos >= BUFF_SIZE){m_iReadPos = 0;}// 设置缓冲区未满的条件变量pthread_cond_signal(&m_notFull);pthread_mutex_unlock(&m_lock);}private:static const int BUFF_SIZE = 32;Type m_buffer[BUFF_SIZE];int m_iReadPos;int m_iWritePos;pthread_mutex_t m_lock;pthread_cond_t m_notEmpty;pthread_cond_t m_notFull;};}}


0 0