这里实现一个基于数组的线程安全的循环队列
来源:互联网 发布:淘宝店铺基本设置在哪 编辑:程序博客网 时间: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
- 这里实现一个基于数组的线程安全的循环队列
- 基于数组的循环队列
- 基于数组的循环队列
- 笔记七:基于数组的循环队列的实现
- 线程安全的循环队列缓冲区
- 基于数组的循环队列(C++模板实现)
- 数据结构之——基于数组实现的循环队列
- 循环队列的数组实现
- 循环队列的数组实现!!
- 循环数组队列的实现
- 队列的数组实现(循环队列)
- 基于数组的队列实现
- 基于数组的队列实现
- 循环数组实现一个队列
- 基于condition 实现的线程安全的优先队列(python实现)
- C++ 实现线程安全的任务队列
- c++11 线程安全的队列实现
- java实现线程安全的队列
- 数据挖掘基本概念
- iOS duplicate symbol _main in:问题解决
- hd 2017 字符串统计
- 巴什博弈(Bash Game)
- Web开发初探(二) HTML基础
- 这里实现一个基于数组的线程安全的循环队列
- hd 2565 放大的X
- 嵌入式驱动开发流程
- Java开发工具及环境配置
- hd 2017 统计字符串 逐个读取字符法注意getchar();
- Red Hat Enterprise Linux 7的新功能
- hd 3783 ZOJ
- ie8下面处理 new Date()的问题
- ACM学习笔记之 数学问题----素数