这里实现一个基于数组的线程安全的循环队列

来源:互联网 发布:淘宝店铺基本设置在哪 编辑:程序博客网 时间:2024/05/29 07:38

具体代码如下:

#include<pthread.h>#include<iostream>using namespace std;#define QUEUESIZE 128template<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;elsecout<<"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

0 0
原创粉丝点击