页面加载中,请稍候
来源:嵌入式专栏发布时间:2022-10-261648浏览
询问 AI
作者 | strongerHuang
环形队列
环形队列是在实际编程极为有用的数据结构,它是一个首尾相连的FIFO的数据结构,采用数组的线性空间,数据组织简单,能很快知道队列是否满为空,能以很快速度的来存取数据。
环形队列的关键是判断队列为空,还是为满。当tail追上head时,队列为满时;当head追上tail时,队列为空。但如何知道谁追上谁,还需要一些辅助的手段来判断.如何判断环形队列为空,为满有两种判断方法:a.附加一个标志位tagtypedef struct ringq{ int head; /* 头部,出队列方向*/ int tail; /* 尾部,入队列方向*/ int tag ; int size ; /* 队列总尺寸 */ int space[RINGQ_MAX]; /* 队列空间 */}RINGQ;
q->head = q->tail = q->tag = 0;( q->head == q->tail) (q->tag == 0) ((q->head == q->tail) (q->tag == 1))q->tail = (q->tail + 1) % q->size ;q->head = (q->head + 1) % q->size#ifndef __RINGQ_H__#define __RINGQ_H__
#ifdef __cplusplusextern "C" {#endif
#define QUEUE_MAX 20
typedef struct ringq{ int head; /* 头部,出队列方向*/ int tail; /* 尾部,入队列方向*/ int tag ; /* 为空还是为满的标志位*/ int size ; /* 队列总尺寸 */ int space[QUEUE_MAX]; /* 队列空间 */}RINGQ;
/* 第一种设计方法: 当head == tail 时,tag = 0 为空,等于 = 1 为满。*/
extern int ringq_init(RINGQ * p_queue);
extern int ringq_free(RINGQ * p_queue);
/* 加入数据到队列 */extern int ringq_push(RINGQ * p_queue,int data);
/* 从队列取数据 */extern int ringq_poll(RINGQ * p_queue,int *p_data);
#define ringq_is_empty(q) ( (q->head == q->tail) (q->tag == 0))
#define ringq_is_full(q) ( (q->head == q->tail) (q->tag == 1))
#define print_ringq(q) printf("ring head %d,tail %d,tag %d\n", q->head,q->tail,q->tag);#ifdef __cplusplus}#endif
#endif /* __RINGQ_H__ */
#include <stdio.h>#include "ringq.h"
int ringq_init(RINGQ * p_queue){ p_queue->size = QUEUE_MAX ;
p_queue->head = 0; p_queue->tail = 0;
p_queue->tag = 0;
return 0;}
int ringq_free(RINGQ * p_queue){ return 0;}
int ringq_push(RINGQ * p_queue,int data){ print_ringq(p_queue);
if(ringq_is_full(p_queue)) {
printf("ringq is full\n"); return -1; }
p_queue->space[p_queue->tail] = data;
p_queue->tail = (p_queue->tail + 1) % p_queue->size ;
/* 这个时候一定队列满了*/ if(p_queue->tail == p_queue->head) { p_queue->tag = 1; }
return p_queue->tag ; }
int ringq_poll(RINGQ * p_queue,int * p_data){ print_ringq(p_queue); if(ringq_is_empty(p_queue)) {
printf("ringq is empty\n"); return -1; }
*p_data = p_queue->space[p_queue->head];
p_queue->head = (p_queue->head + 1) % p_queue->size ;
/* 这个时候一定队列空了*/ if(p_queue->tail == p_queue->head) { p_queue->tag = 0; } return p_queue->tag ;}
消息队列
在RTOS中基本都有消息队列这个组件,也是使用最常见的组件之一。
xQueue = xQueueCreate(QUEUE_LEN, QUEUE_SIZE);
“环形队列”和“消息队列”的异同


新闻来源:嵌入式专栏,文中所述为作者独立观点,不代表icspec立场。更多精彩资讯请下载icspec App。如对本稿件有异议,请联系微信客服specltkj。
暂无评论哦,快来评论一下吧!
2026-06-03

2026-07-03