C语言实现消息队列模拟:模拟 Windows 系统进程消息处理
使用 C 语言模拟消息队列
在 Windows 系统中,每个进程都维护着一个消息队列。当进程中发生特定事件,例如鼠标点击、文字改变等,系统会将该事件对应的消息添加到队列中。进程会循环地从队列中按照优先级获取消息并进行处理。优先级值越低,优先级越高。
本文将使用 C 语言编写一个程序来模拟消息队列的行为,实现消息的添加和获取功能。
代码实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_QUEUE_SIZE 100000
typedef struct {
char name[11];
int priority;
} Message;
typedef struct {
Message messages[MAX_QUEUE_SIZE];
int front;
int rear;
} Queue;
void initQueue(Queue *q) {
q->front = 0;
q->rear = -1;
}
int isQueueEmpty(Queue *q) {
return q->rear < q->front;
}
int isQueueFull(Queue *q) {
return q->rear - q->front + 1 == MAX_QUEUE_SIZE;
}
void enqueue(Queue *q, Message msg) {
if (isQueueFull(q)) {
printf("Queue is full. Cannot enqueue.\n");
return;
}
int i;
for (i = q->rear; i >= q->front; i--) {
if (msg.priority >= q->messages[i].priority) {
break;
}
q->messages[i + 1] = q->messages[i];
}
q->messages[i + 1] = msg;
q->rear++;
}
Message dequeue(Queue *q) {
Message msg;
if (isQueueEmpty(q)) {
strcpy(msg.name, "EMPTY QUEUE!");
msg.priority = -1;
return msg;
}
msg = q->messages[q->front];
q->front++;
return msg;
}
int main() {
int N;
scanf("%d", &N);
Queue q;
initQueue(&q);
char cmd[4];
char name[11];
int priority;
for (int i = 0; i < N; i++) {
scanf("%s", cmd);
if (strcmp(cmd, "PUT") == 0) {
scanf("%s %d", name, &priority);
Message msg;
strcpy(msg.name, name);
msg.priority = priority;
enqueue(&q, msg);
} else if (strcmp(cmd, "GET") == 0) {
Message msg = dequeue(&q);
printf("%s\n", msg.name);
}
}
return 0;
}
输入格式
输入首先给出正整数 N(≤10^5),随后 N 行,每行给出一个指令——GET 或 PUT,分别表示从队列中取出消息或将消息添加到队列中。
如果指令是 PUT,后面就有一个消息名称,以及一个正整数表示消息的优先级,此数越小表示优先级越高。消息名称是长度不超过 10 个字符且不含空格的字符串。题目保证队列中消息的优先级无重复,且输入至少有一个 GET。
输出格式
对于每个 GET 指令,在一行中输出消息队列中优先级最高的消息的名称和参数。如果消息队列中没有消息,输出 EMPTY QUEUE!。对于 PUT 指令则没有输出。
注意
该程序假设输入是符合要求的,即不会出现无效的指令或格式错误。在实际应用中,应该添加适当的输入验证和错误处理机制。
该程序模拟了 Windows 系统中的消息队列机制,使用 C 语言实现了消息的添加和获取功能。通过学习该程序,可以加深对消息队列工作原理的理解。
原文地址: http://www.cveoy.top/t/topic/bmyi 著作权归作者所有。请勿转载和采集!