具体代码如下:
#include<pthread.h>
#include<iostream>
using namespace std;
#define QUEUESIZE 128
template<class object>
class ThreadSafeQueue
{
private:
pthread_mutex_t m_lock;
int m_front;
int m_rear;
object m_data[QUEUESIZE];
public:
ThreadSafeQueue():m_front(0),m_rear(0)
{
pthread_mutex_init(&m_lock,NULL);
}
bool EnQueue(object data)
{
pthread_mutex_lock(&m_lock);
if(isFull())
{
cout<<"The queue is full!"<<endl;
pthread_mutex_unlock(&m_lock);
return false;
}
m_data[m_rear] = data;
m_rear = (m_rear+1)%QUEUESIZE;
pthread_mutex_unlock(&m_lock);
return true;
}
bool DeQueue(object& data)
{
pthread_mutex_lock(&m_lock);
if(isEmpty())
{
cout<<"The queue is empty!"<<endl;
pthread_mutex_unlock(&m_lock);
return false;
}
data = m_data[m_front];
m_front = (m_front+1)%QUEUESIZE;
pthread_mutex_unlock(&m_lock);
return true;
}
bool isFull()
{
if((m_rear+1)%QUEUESIZE == m_front)
return true;
return false;
}
bool isEmpty()
{
if(m_rear == m_front)
return true;
return false;
}
~ThreadSafeQueue()
{
pthread_mutex_destroy(&m_lock);
}
};
int main(int argc, char* argv[])
{
ThreadSafeQueue<int> testQueue;
int out = 0;
if(!testQueue.DeQueue(out))
cout<<"DeQueue false!"<<endl;
else
cout<<"DeQueue true out="<<out<<endl;
testQueue.EnQueue(12);
testQueue.EnQueue(13);
testQueue.EnQueue(14);
if(!testQueue.DeQueue(out))
cout<<"DeQueue false!"<<endl;
else
cout<<"DeQueue true out="<<out<<endl;
if(!testQueue.DeQueue(out))
cout<<"DeQueue false!"<<endl;
else
cout<<"DeQueue true out="<<out<<endl;
if(!testQueue.DeQueue(out))
cout<<"DeQueue false!"<<endl;
else
cout<<"DeQueue true out="<<out<<endl;
if(!testQueue.DeQueue(out))
cout<<"DeQueue false!"<<endl;
else
cout<<"DeQueue true out="<<out<<endl;
return 0;
}
g++ queue.c -lpthread