trafficQueue.h 2 KB
#ifndef _TRAFFIC_QUEUE_H
#define _TRAFFIC_QUEUE_H

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>

#define QUEUESIZE 15  	//缓存队列的大小
#define BLOCKSIZE 1024*5  //每一块的大小

pthread_mutex_t mut=PTHREAD_MUTEX_INITIALIZER;

//static int enResultCount = 0;
//static int deResultCount = 0;

typedef struct{
	char data[QUEUESIZE][BLOCKSIZE];
	int front;
	int rear;
	int count;
}CirQueue;

void Initial(CirQueue *Q)
{
	pthread_mutex_lock(&mut);
	Q->front=Q->rear=0;
	Q->count=0;
	pthread_mutex_unlock(&mut);
}

int IsEmpty(CirQueue *Q)
{
	return Q->front==Q->rear;
}

int IsFull(CirQueue *Q)
{
	return Q->count == QUEUESIZE-1;
}

void EnQueue(CirQueue *Q, char *inStr)
{
pthread_mutex_lock(&mut);
	if(IsFull(Q))  //如果队列满了先删掉最初入队列的元素
	{
		printf("\033[1;31;40m **********队列已满,删除队首元素********** \033[0m\n");
		Q->front = (Q->front+1)%QUEUESIZE;
		Q->count--;
	}
	memset(Q->data[Q->rear], 0, BLOCKSIZE);
	memcpy(Q->data[Q->rear], inStr, strlen(inStr));
	Q->count++;
	Q->rear=(Q->rear+1)%QUEUESIZE;      //循环意义下将尾指针加1
pthread_mutex_unlock(&mut);
//	printf("\033[1;34;40m >>>>>>>>>>>>>>>>插入一条数据:nCount=%d,front=%d,rear=%d, enResultCount=%d<<<<<<<<<<<<<<<<<< \033[0m\n",
//			Q->count,Q->front,Q->rear, ++enResultCount);
}

int DeQueue(CirQueue *Q, char** outStr)
{
	int ret = 0;
pthread_mutex_lock(&mut);
	if(IsEmpty(Q))
	{
//		printf("队列为空,无法取出数据\n");
		ret = -1;
	}
	else
	{
		*outStr=Q->data[Q->front];
		Q->count--;
		Q->front=(Q->front+1)%QUEUESIZE;   //循环意义下的头指针加1

	}
pthread_mutex_unlock(&mut);
//	if(ret == 0)
//	{
//		printf("\033[1;32;40m >>>>>>>>>>>>>>>>取出一条数据:nCount=%d,front=%d,rear=%d, deResultCount=%d<<<<<<<<<<<<<<<<<< \033[0m\n",
//				Q->count,Q->front,Q->rear, ++deResultCount);
//	}
	return ret;
}

char* Front(CirQueue *Q)
{
	if(IsEmpty(Q))
	{
//		printf("队列为空"); //下溢,退出运行
		exit(1);
	}
	return Q->data[Q->front];
}
#endif