一个支持多线程同步循环队列的实现

队列元素为一个无符字符数组(即字节数组)。循环队列中只存放该数组的地址。这个地址指向一个存储区域,该存储区的结构为:
                                    _______________________________________________
                                    |数组长度(4B)|数组内容(由前面的长度决定长度)|
                                    ---------------------------------------------------------------
这个循环队列支持多线程同步操作,对队列改动时,有互斥锁mutex防止不同步。

工作环境:
linux 9.0
编译:
g++ BytesQueue.cpp main.cpp -o main -lpthread

下面是代码部分:
俩个main.cpp函数,前一个为一般单线程应用。后一个为多线程应用。

/*
 BytesQueue.h
 zhangggdlt
 2004/11/15
 
 to realize a queue storing bytes array.
*/
#ifndef _BYTES_QUEUE_H
#define _BYTES_QUEUE_H

#include <pthread.h>
#include <unistd.h>

#define OPERATION_OK 0
#define QUEUE_FULL -1
#define QUEUE_EMPTY -2
#define INCREASE_FAILED -3
#define NO_AREA -4
#define POINT_NULL -5
#define FAILED_LOCK -6


typedef int ERR_NUMBER;
typedef unsigned char uint_8;

/*
 The class BytesQueue is used to realize store an unsigned char array into the queue which
 sustain mutiple thread and sycronization.
 This queue is a cycle queue. The size of the queue can be set when it is constructed and you
 can also increas the size of the queue during the application.
*/
class BytesQueue
{
private:
 int _size;
 int _head;
 int _rear;
 uint_8 **_buffer;
 pthread_mutex_t QueMutex;
 
public:
 BytesQueue(int size=512);
 ERR_NUMBER increaseSize(int size=512);
 ERR_NUMBER inQueue(const uint_8 *data, int len);
 ERR_NUMBER outQueue(uint_8 *data, int &len);
 
 void destroy();
 void errMessage(ERR_NUMBER err);
 void showBytesQueue(BytesQueue& bq);
};

 

#endif //_BYTES_QUEUE_H

——————————————————————————————————————
/*
 BytesQueue.cpp
 zhangggdlt
 2004/12/9
 
 to realize a stack storing bytes array which sustain the mutitread and sycronization.
*/
#include <stdio.h>
#include <string.h>
#include "BytesQueue.h"


/*
 Constructor.
 This BytesQueue can sustain sycronization among the mutiThread.
 It means you can use this data structure under mutithread.
*/
BytesQueue::BytesQueue(int size) //size = 512
{
 this->_size = size;
 this->_buffer = new (uint_8*)[this->_size];
 this->_head = 0;
 this->_rear = 0;
 pthread_mutex_init(&QueMutex,

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值