C实现的同步互斥Queue
#ifndef __MYQUEUE_H_ #define __MYQUEUE_H_ #include <pthread.h> #include <iostream> #include <queue> #include <algorithm> #include <string> using namespace std; template <class T> class Queue { public: Queue(int iMax); ~Queue(); bool Push(T &stData); bool Front(T &stData); bool Fetch(T &stData); void Pop(); int Size(); private: queue<T> stQueue; pthread_mutex_t stMutex; pthread_cond_t stEmptyCond; pthread_cond_t stFullCond; int _iMax; }; template <class T> Queue<T>::Queue(int iMax) { _iMax = iMax; } template <class T> Queue<T>::~Queue() { } template <class T> bool Queue<T>::Push(T &stData) { pthread_mutex_lock(&stMutex); while(stQueue.size() >= _iMax) { pthread_cond_wait(&stFullCond, &stMutex); } stQueue.push(stData); pthread_cond_signal(&stEmptyCond); pthread_mutex_unlock(&stMutex); return true; } template <class T> int Queue<T>::Size() { return stQueue.size(); } template <class T> void Queue<T>::Pop() { pthread_mutex_lock(&stMutex); if(!stQueue.empty()) { stQueue.pop(); } pthread_mutex_unlock(&stMutex); } template <class T> bool Queue<T>::Front(T &stData) { bool bRet = false; pthread_mutex_lock(&stMutex); if(!stQueue.empty()) { stData = stQueue.front(); bRet = true; } pthread_mutex_unlock(&stMutex); return bRet; } template <class T> bool Queue<T>::Fetch(T &stData) { bool bRet = false; pthread_mutex_lock(&stMutex); while(stQueue.empty()) { pthread_cond_wait(&stEmptyCond, &stMutex); } stData = stQueue.front(); stQueue.pop(); pthread_cond_signal(&stFullCond); pthread_mutex_unlock(&stMutex); return true; } #endif