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

本文介绍了一种使用C++实现的线程安全队列,包括队列的入队、出队操作,以及队列是否已满和是否为空的判断。通过使用互斥锁保证了队列在多线程环境下的安全。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

具体代码如下:

#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
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值