| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- #include <stdio.h>
- #include <stdlib.h>
- #include "sqqueue.h"
-
- queue_t pkt_creat_sqqueue(int len)
- {
- queue_t q;
- if ((q = (queue_t)malloc(sizeof(struct queue))) == NULL)
- {
- printf("malloc failed!\n");
- return NULL;
- }
-
- if ((q->msg = (message_t)malloc(sizeof(struct message) * len)) == NULL)
- {
- printf("malloc failed!\n");
- return NULL;
- }
-
- q->front = q->rear = len - 1;
- q->len = len;
- return q;
- }
-
- int pkt_empty_sqqueue(queue_t q)
- {
- return q->front == q->rear;
- }
-
- int pkt_full_sqqueue(queue_t q)
- {
- return (q->rear + 1) % q->len == q->front; /* 空出一个消息位置判断为满,队列最大装len - 1个 */
- }
-
- int pkt_put_message_sqqueue(queue_t q, message_t m)
- {
- if (pkt_full_sqqueue(q))
- {
- printf("squeue is full!\n");
- return -1;
- }
-
- q->rear = (q->rear + 1) % q->len; /* first rear++ */
- q->msg[q->rear] = *m;
- return 0;
- }
-
- int pkt_take_message_sqqueue(queue_t q, message_t m)
- {
- if (pkt_empty_sqqueue(q))
- {
- printf("squeue is empty!\n");
- return -1;
- }
-
- q->front = (q->front + 1) % q->len; /* frist front++ */
- *m = q->msg[q->front];
- return 0;
- }
-
- int pkt_show_sqqueue(queue_t q)
- {
- int i;
- for (i = (q->front + 1) % q->len; i != (q->rear + 1) % q->len; i = (i + 1) % q->len)
- {
- printf("queue[%d] = %d\n", i, q->msg[i].data);
- }
-
- return 0;
- }
-
- int main(int argc, char **argv)
- {
- queue_t q;
-
- q = pkt_creat_sqqueue(10);
-
- struct message m;
- for (int i = 1; i <= 10; i++)
- {
- m.data = i;
- printf("put %d\n", m.data);
- pkt_put_message_sqqueue(q, &m);
- }
-
- while (!pkt_empty_sqqueue(q))
- {
- pkt_take_message_sqqueue(q, &m);
- printf("take = %d\n", m.data);
- }
-
- pkt_show_sqqueue(q);
-
- return 0;
- }
|