一、实现原理如下图所示
1.队列是满的条件为g_in=3且g_out=0,即下一个要放入数据的位置等于当前要取数据的位置(g_in+1 == g_out)
2.队列是空的条件为g_in=0且g_out=0,
或g_in=1且g_out=1,
或g_in=2且g_out=2,
或g_in=3且g_out=3,即当前要取数据的位置等于当前要放数据的位置(g_out == g_in)
二、代码实现如下
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 5 #define QUEUE_SIZE_MAX 4 6 #define MY_BUF_SIZE 128 7 8 typedef struct{ 9 int type; 10 int reserve; 11 int buf[MY_BUF_SIZE]; 12 }T_QUEUE; 13 14 static T_QUEUE g_que[QUEUE_SIZE_MAX]; 15 16 int g_in,g_out; 17 18 // 队列初始化 19 void init_queue(void) 20 { 21 g_in = 0; 22 g_out = 0; 23 } 24 25 /********************************************************************************** 26 * @brief Function 放入数据到队列 27 * 28 * @param[in] pNode 要放入的数据 29 * 30 * @return value ret 返回值为0放入数据成功,返回为1则队列溢出放入失败 31 **********************************************************************************/ 32 int put_into_queue(T_QUEUE *pNode) 33 { 34 OS_ENTER_CRITICAL(); 35 int nextPos; 36 int ret=0; 37 38 nextPos = g_in +1; 39 if(nextPos >= QUEUE_SIZE_MAX) 40 nextPos = 0; 41 42 if(nextPos != g_out) 43 { 44 memcpy(&g_que[g_in], pNode, sizeof(T_QUEUE)); 45 g_in = nextPos; 46 ret = 0; 47 } 48 else 49 { 50 ret = 1; //队列满则溢出 51 } 52 OS_EXIT_CRITICAL(); 53 54 return ret; 55 } 56 57 /********************************************************************************** 58 * @brief Function 从队列中取出数据 59 * 60 * @param[out] pNode 取出数据所存放的地址 61 * 62 * @return value ret 返回值为0,则取出数据成功;返回为1,则队列为空,取出失败 63 **********************************************************************************/ 64 int get_from_queue(T_QUEUE *pNode) 65 { 66 int nextPos; 67 int ret=0; 68 if(g_out!=g_in) 69 { 70 nextPos = g_out + 1; 71 if(nextPos >= MAX_MSG_QUEUE) 72 nextPos = 0; 73 memcpy(pNode,&g_que[g_out],sizeof(T_QUEUE)); 74 g_out = nextPos; 75 ret = 0; 76 } 77 else 78 { 79 ret = 1; //队列为空 80 } 81 82 return ret; 83 }