typedef struct QUEUE{
//struct QUEUE *Qnext;
void ** QStart;
void **QEnd;
void **QIn;
void **QOut;
unsigned int QSize;
unsigned int QEntries;
}queue;
queue *queue_create(int size)
{
queue *q = (queue *)malloc(sizeof(queue));
if(q==NULL)
{
printf("error\n");
return NULL;
}
void **datatbl = (void **)malloc(size*sizeof(void *));// 动态分配的是连续空间内存,和数组效果差不多。
if(datatbl == NULL)
{
free(q);
printf("error\n");
return NULL;
}
q->QEntries = 0;
q->QSize = size;
q->QStart = &datatbl[0];
q->QEnd = &datatbl[size-1];
q->QIn = q->QStart;
q->QOut = q->QStart;
return q;
}
void queue_destory(queue *q)
{
if(q->QStart!=NULL)
{
free(q->QStart);
}
if(q!=NULL)
{
free(q);
}
return;
}
void *queue_pend(queue *q)
{
void *data = NULL;
if(q->QEntries==0)
{
return NULL;
}
q->QEntries--;
data = *q->QOut;
if(q->QOut==q->QEnd)
{
q->QOut = q->QStart;
}
else
{
q->QOut++;
}
return data;
}
int queue_post(queue *q, void *data)
{
if(q->QEntries==q->QSize)
{
return 1;
}
q->QEntries++;
*q->QIn = data;
if(q->QIn == q->QEnd)
{
q->QIn = q->QStart;
}
else
{
q->QIn++;
}
return 0;
}
测试代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
void *data;
int data_len;
}q_data_type;
int main()
{
queue *msg_q = queue_create(4);
if(msg_q==NULL)
{
printf("create queue fail\n");
return 1;
}
q_data_type msg[10] = { {"111",4}, {"2222",5}, {"33333",6}, {"444444",7}, {"5555555",8}, {"1",2}, {"22",3},{"334",4}, {"4445",5},{"55556",6} };
q_data_type *msg_ptr = NULL;
int i = 0;
for(i=0; i<4; i++)
{
if(queue_post(msg_q, (void *)&msg[i])!=0)
{
printf("post msg[%d] fail\n", i);
}
else
{
printf("post msg[%d] success: [%s]\n", i, (char *)msg[i].data);
}
}
for(i=0; i<3; i++)
{
if((msg_ptr=(q_data_type *)queue_pend(msg_q)) == NULL)
{
printf("Get msg[%d] fail\n", i);
}
else
{
printf("Get msg[%d] success: [%s]\n", i,(char *)msg_ptr->data);
}
}
for(i=4; i<5; i++)
{
if(queue_post(msg_q, (void *)&msg[i])!=0)
{
printf("post msg[%d] fail\n", i);
}
else
{
printf("post msg[%d] success:[%s]\n", i, (char *)msg[i].data);
}
}
for(i=0; i<2; i++)
{
if((msg_ptr=(q_data_type *)queue_pend(msg_q)) == NULL)
{
printf("Get msg[%d] fail\n", i);
}
else
{
printf("Get msg[%d] success: [%s]\n", i,(char *)msg_ptr->data);
}
}
for(i=0; i<2; i++)
{
if((msg_ptr=(q_data_type *)queue_pend(msg_q)) == NULL)
{
printf("Get msg[%d] fail\n", i);
}
else
{
printf("Get msg[%d] success: [%s]\n", i,(char *)msg_ptr->data);
}
}
return 0;
}
运行结果:
把队列的大小给改成1,运行结果:
queue *msg_q = queue_create(1);
把队列的大小给改成2,运行结果:
queue *msg_q = queue_create(2);