循环队列的特点什么的网上资料多,这里就直接上代码吧.
1 声明及定义
-
typedef struct
-
{
-
size_t size; /* 初始化后放入队列的容量 */
-
-
volatile unsigned int front;
-
volatile unsigned int rear;
-
}circularqueuehead_t;
-
-
typedef struct __attribute__((packed))
-
{
-
unsigned char content[LENGTH]; /* 队列元素的内容 */
-
}atom_t;
-
-
static circularqueuehead_t *g_cq_head; /* 初始化后指向队列头 */
-
static atom_t *g_cq; /* 初始化后指向队列本身 */
2 算法-1
-
/************************************************
-
* Name : cq_write/cq_read
-
* Description :
-
* Parameters : atom_t *operand
-
* Retrun : 0. write/read success
-
* 1. write - queue is full
-
* read - queue is empty
-
* Developer : zhonghaohua
-
* Created : Wed Oct 30 10:59:46 2013
-
************************************************/
-
int cq_write( atom_t *srt)
-
{
-
unsigned int nextpost = ( g_cq_head->front + 1) % g_cq_head->size;
-
-
if( nextpost != g_cq_head->rear ) {
-
g_cq[nextpost] = *srt;
-
g_cq_head->front = nextpost;
-
-
return 0;
-
}
-
else {
-
return 1;
-
}
-
}
-
-
int cq_read( atom_t *srt)
-
{
-
if( g_cq_head->rear != g_cq_head->front) {
-
g_cq_head->rear = (g_cq_head->rear + 1) % g_cq_head->size;
-
*srt = g_cq[g_cq_head->rear];
-
-
return 0;
-
}
-
else {
-
return 1;
-
}
-
}
3 算法-2
-
-
/************************************************
-
* Name : cq_write/cq_read
-
* Description :
-
* Parameters : atom_t *operand
-
* Retrun : 0. write/read success
-
* 1. write - queue is full
-
* read - queue is empty
-
* Developer : zhonghaohua
-
* Created : Wed Oct 30 10:59:46 2013
-
************************************************/
-
int cq_write( atom_t *sa)
-
{
-
unsigned int nextpost = ( g_cq_head->front + 1) % g_cq_head->size;
-
-
if( nextpost != g_cq_head->rear ) {
-
g_cq[g_cq_head->front] = *sa;
-
g_cq_head->front = nextpost;
-
-
return 0;
-
}
-
else {
-
return 1;
-
}
-
}
-
-
int cq_read( atom_t *sa)
-
{
-
if( g_cq_head->rear != g_cq_head->front) {
-
*sa = g_cq[g_cq_head->rear];
-
g_cq_head->rear = (g_cq_head->rear + 1) % g_cq_head->size;
-
-
return 0;
-
}
-
else {
-
return 1;
-
}
-
}
4 说明
算法-1 和 算法-2 差别不大
相同: 1) 都以 front + 1 == rear 作为队列满的标记
2) 都以 rear == front 作为队列空的标记
差别: 1) 算法-1: write 先[front + 1] = *src,后(front++); read 先(rear++), 后 *src = [rear].
2) 算法-2: write 先[front] = *src, 后(front++); read 先 *src = [rear],后(rear++).
在front/rear都初始化为0时, 算法-1在第一次读写时, 队列[0]会被跳过.
END.
阅读(1469) | 评论(0) | 转发(0) |