用c语言写消息队列代码且能在Dev C++运行
时间: 2024-05-12 21:20:47 浏览: 79
以下是一个基本的消息队列的C语言实现,可以在Dev C++中运行:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_QUEUE_SIZE 100
typedef struct {
int id;
char message[50];
} Message;
typedef struct {
Message messages[MAX_QUEUE_SIZE];
int front, rear;
} Queue;
void initQueue(Queue *q) {
q->front = q->rear = 0;
}
int isQueueEmpty(Queue *q) {
return q->front == q->rear;
}
int isQueueFull(Queue *q) {
return (q->rear + 1) % MAX_QUEUE_SIZE == q->front;
}
void enqueue(Queue *q, Message m) {
if (isQueueFull(q)) {
printf("Queue is full!\n");
return;
}
q->messages[q->rear] = m;
q->rear = (q->rear + 1) % MAX_QUEUE_SIZE;
}
Message dequeue(Queue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty!\n");
exit(1);
}
Message m = q->messages[q->front];
q->front = (q->front + 1) % MAX_QUEUE_SIZE;
return m;
}
int main() {
Queue q;
initQueue(&q);
Message m1 = {1, "Hello"};
Message m2 = {2, "World"};
enqueue(&q, m1);
enqueue(&q, m2);
while (!isQueueEmpty(&q)) {
Message m = dequeue(&q);
printf("Message %d: %s\n", m.id, m.message);
}
return 0;
}
```
阅读全文