一、循环队列
我们可以把每一则消息带有的信息放到结构体里面。这样,每个结构体就是队列的一个成员。接收消息的线程把消息包装成一个结构体然后在队列(数组)的尾部加上,处理消息的线程取出队列的头部来解析处理,每次解析处理完一则消息,就把消息从队列的头部移除。
所以,我们要定义一个结构体数组,结构体里面还能包含结构体等,只要项目需要,都可以拓展。
程序模板比较简单,关键是知道怎么运用到项目中。
其中需要注意的点是循环队列如何判断空还是满。假设循环队列长度为5,当头指针和尾指针指向同一个地方,我们设为空。当有元素入队,尾指针指向下一个元素,当有元素出队,头指针指向下一个元素。当指向的元素为5时,下一个元素为0。
这样,得出的结论是,当队列为满时,头指针和尾指针是相等的,这和队列为空的时候是一样的。不信,画画图看看。
那怎么处理呢?
为了区别空队列和满队列,数组多加一个元素,这个元素是不确定的,是可以移动的,它将保证当队列为满时,还空留了一个位置。说起来比较抽象,看以下代码:
所以,通过在循环数组中加多了一个元素,就能够区分队列是空的还是满的。
大致的模板如下:
#include <stdio.h>
#include <string.h>
//构造不完全填满循环数组,以便区分队列为空还是满。
#define QUEUE_LEN 16
#define ARRAR_SIZE (QUEUE_LEN + 1)
typedef struct student
{
int math;
int English;
char name[32];
} student;
#define QUEUE_TYPE student
typedef enum BOOL_
{
false = 0,
true = 1,
}bool;
//static使全局变量只在本文件中使用
static student studentTable[ARRAR_SIZE];//定义结构体数组
static unsigned int front; //指向队头元素
static unsigned int tail; //指向队尾元素的下一个
bool IsQueueEmpty(void)
{
return (front == tail);
}
bool IsQueueFull()
{
return ((tail + 1) % ARRAR_SIZE == front);
}
bool queueInsert(QUEUE_TYPE value)
{
if(IsQueueFull())
return false;
studentTable[tail] = value;
tail = (tail + 1) % ARRAR_SIZE;
return true;
}
bool queueDelete()
{
if(IsQueueEmpty())
return false;
front = (front + 1) % ARRAR_SIZE;
return true;
}
//测试程序
int main(int argc, char *argv[])
{
student stu;
stu.math = 99;
stu.English = 98;
char name[32]= "xiaoming";
memcpy(stu.name,name,sizeof(name));
queueInsert(stu);
stu.math = 61;
stu.English = 60;
memset(name,0,sizeof(name));
sprintf(name,"xiaohong",sizeof(name));
memcpy(stu.name,name,sizeof(name));
queueInsert(stu);
printf("front = %d,tail = %d,name = %s\n",front,tail,studentTable[front].name);
queueDelete();
printf("front = %d,tail = %d,name = %s\n",front,tail,studentTable[front].name);
return 0;
}
whaosoft aiot http://143ai.com