队列元素为一个无符字符数组(即字节数组)。循环队列中只存放该数组的地址。这个地址指向一个存储区域,该存储区的结构为:
_______________________________________________
|数组长度(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, NULL);
}
/*
You can use this number fuction to increase the size of the queue.
The data will not be lost during the increasement.
*/
ERR_NUMBER BytesQueue::increaseSize(int size) //size = 512
{
uint_8 **temp;
int eleCount = (this->_rear - this->_head + 1 + this->_size) % this->_size;
int tempSize = this->_size;
int i,j;
this->_size += size;
if(!(temp = new (uint_8*)[

本文介绍了如何实现一个支持多线程同步操作的循环队列BytesQueue,该队列用于存储无符号字符数组的指针。队列结构包括数组长度和内容,具有增加队列大小的功能,并在Linux环境下使用互斥锁进行同步。代码包括BytesQueue类的定义和实现,以及多线程应用示例。
2022

被折叠的 条评论
为什么被折叠?



