当前位置: 首页 > news >正文

环形队列

代码片段

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>#define MAX_MSG_SIZE 256
#define QUEUE_EMPTY -1
#define QUEUE_FULL -2// 消息结构体
typedef struct {long mtype;           // 消息类型,Linux 消息队列中用于区分消息char mtext[MAX_MSG_SIZE]; // 消息内容
} Message;// 基于环形队列的消息队列结构体
typedef struct {Message *messages;    // 存储消息的环形缓冲区int front;            // 队头指针int rear;             // 队尾指针int capacity;         // 队列容量int size;             // 当前消息数量
} MessageQueue;// 创建消息队列
MessageQueue* msg_queue_create(int capacity) {if (capacity <= 0) {fprintf(stderr, "Error: Capacity must be positive\n");return NULL;}MessageQueue *mq = (MessageQueue*)malloc(sizeof(MessageQueue));if (!mq) {perror("Memory allocation failed for message queue");return NULL;}mq->messages = (Message*)malloc(sizeof(Message) * capacity);if (!mq->messages) {perror("Memory allocation failed for messages");free(mq);return NULL;}mq->front = 0;mq->rear = 0;mq->capacity = capacity;mq->size = 0;printf("Message queue created with capacity %d\n", capacity);return mq;
}// 检查消息队列是否为空
bool msg_queue_is_empty(MessageQueue *mq) {return mq->size == 0;
}// 检查消息队列是否已满
bool msg_queue_is_full(MessageQueue *mq) {return mq->size == mq->capacity;
}// 发送消息(入队)
int msg_send(MessageQueue *mq, long msg_type, const char *msg_text) {if (msg_queue_is_full(mq)) {printf("Message queue is full. Cannot send message.\n");return QUEUE_FULL;}if (strlen(msg_text) >= MAX_MSG_SIZE) {fprintf(stderr, "Error: Message text too long (max %d characters)\n", MAX_MSG_SIZE - 1);return -3;}// 构造消息Message msg;msg.mtype = msg_type;strncpy(msg.mtext, msg_text, MAX_MSG_SIZE - 1);msg.mtext[MAX_MSG_SIZE - 1] = '\0';// 存入环形缓冲区mq->messages[mq->rear] = msg;mq->rear = (mq->rear + 1) % mq->capacity;mq->size++;printf("Message sent: [type=%ld] %s\n", msg.mtype, msg.mtext);return 0;
}// 接收消息(出队),按先进先出顺序,忽略消息类型(简化版)
int msg_receive(MessageQueue *mq, long *msg_type, char *msg_text, int max_len) {if (msg_queue_is_empty(mq)) {printf("Message queue is empty. Cannot receive message.\n");return QUEUE_EMPTY;}// 从队头取出消息Message msg = mq->messages[mq->front];mq->front = (mq->front + 1) % mq->capacity;mq->size--;if (msg_type) {*msg_type = msg.mtype;}if (msg_text) {strncpy(msg_text, msg.mtext, max_len - 1);msg_text[max_len - 1] = '\0';}printf("Message received: [type=%ld] %s\n", msg.mtype, msg.mtext);return 0;
}// 获取消息队列当前消息数量
int msg_queue_size(MessageQueue *mq) {return mq->size;
}// 销毁消息队列
void msg_queue_destroy(MessageQueue *mq) {if (mq) {free(mq->messages);free(mq);printf("Message queue destroyed\n");}
}// 打印消息队列状态
void msg_queue_print_status(MessageQueue *mq) {printf("Message Queue Status: ");if (msg_queue_is_empty(mq)) {printf("Empty\n");} else if (msg_queue_is_full(mq)) {printf("Full\n");} else {printf("Partially filled\n");}printf("  Capacity: %d, Current size: %d\n", mq->capacity, mq->size);printf("  Front index: %d, Rear index: %d\n", mq->front, mq->rear);if (!msg_queue_is_empty(mq)) {printf("  Messages in queue (from front to rear):\n");int index = mq->front;for (int i = 0; i < mq->size; i++) {printf("    [%d] type=%ld, text='%s'\n",i, mq->messages[index].mtype, mq->messages[index].mtext);index = (index + 1) % mq->capacity;}}
}// 测试函数
int main() {printf("=== Message Queue Based on Circular Queue ===\n\n");// 1. 创建消息队列,容量为5MessageQueue *mq = msg_queue_create(5);if (!mq) {fprintf(stderr, "Failed to create message queue\n");return 1;}msg_queue_print_status(mq);printf("\n");// 2. 发送几条消息printf("--- Sending messages ---\n");msg_send(mq, 1, "Hello, this is the first message");msg_send(mq, 2, "Second message with higher priority");msg_send(mq, 1, "Another message of type 1");msg_send(mq, 3, "Test message number three");msg_send(mq, 2, "Final message before queue is full");msg_queue_print_status(mq);printf("\n");// 3. 尝试发送消息到已满队列printf("--- Attempt to send to full queue ---\n");int result = msg_send(mq, 4, "This should fail");if (result == QUEUE_FULL) {printf("Expected: queue is full, send failed.\n");}msg_queue_print_status(mq);printf("\n");// 4. 接收几条消息printf("--- Receiving messages ---\n");long received_type;char received_text[MAX_MSG_SIZE];for (int i = 0; i < 3; i++) {if (msg_receive(mq, &received_type, received_text, MAX_MSG_SIZE) == 0) {printf("  Received: type=%ld, text='%s'\n", received_type, received_text);}}msg_queue_print_status(mq);printf("\n");// 5. 再发送几条消息,测试环形特性printf("--- Sending more messages (testing circular behavior) ---\n");msg_send(mq, 4, "New message after some dequeues");msg_send(mq, 5, "Another new message");msg_queue_print_status(mq);printf("\n");// 6. 接收剩余的所有消息printf("--- Receiving all remaining messages ---\n");while (!msg_queue_is_empty(mq)) {msg_receive(mq, &received_type, received_text, MAX_MSG_SIZE);}msg_queue_print_status(mq);printf("\n");// 7. 尝试从空队列接收printf("--- Attempt to receive from empty queue ---\n");result = msg_receive(mq, NULL, NULL, 0);if (result == QUEUE_EMPTY) {printf("Expected: queue is empty, receive failed.\n");}// 8. 清理msg_queue_destroy(mq);return 0;
}

看法

  1. 有一点是frontrear会一直递增。

溢出时间计算

以32位有符号int为例:

最大值:2,147,483,647

假设每秒处理10,000次操作:

达到最大值需要:2,147,483,647 / 10,000 ≈ 214,748 秒 ≈ 2,486 天 ≈ 6.8年

对于大多数应用,在可预见的生命周期内不会溢出。

  1. 常用的数据结构之一,好用不必多言。

  2. AI生成的,理解起来很舒服,有种知识进入大脑的感觉。

http://www.jsqmd.com/news/70789/

相关文章:

  • 《关于开始这件事》
  • Office 2024 安装包免费版永久使用+详细安装教程
  • 2025 年 BI 本地私有化部署厂商全景图:企业智能 BI 私有化部署厂商提供的一站式智能 BI 本地化服务指南 - 品牌2026
  • 实验室反应釜/化工反应釜/高压反应釜/磁力反应釜哪家质量好?以及生产厂家推荐 - 品牌推荐大师
  • 实验室反应釜/化工反应釜/高压反应釜/磁力反应釜哪家质量好?以及生产厂家推荐 - 品牌推荐大师
  • 2025年农作物病虫害监测预警系统订制厂家推荐榜单:物联网虫情测报灯‌/病虫害监测系统‌/土壤墒情监测站源头厂家精选 - 品牌推荐官
  • 专业水处理设备/全自动水处理设备/国产水处理设备/选哪家好?求推荐品牌生产厂家或制造商,水处理设备价格由什么因素决定 - 品牌推荐大师
  • 2025口碑好的智能防爆包装封口机供应商TOP5:安全与效能 - myqiye
  • 2025口碑好的智能防爆包装封口机供应商TOP5:安全与效能 - myqiye
  • 沈阳天仁合一科技有限公司的优势在哪?其行业口碑怎样? - mypinpai
  • 国产全自动纯化水设备|全自动超纯水设备:生产商、品牌及厂家推荐 - 品牌推荐大师
  • 2025年琉璃瓦厂家推荐排行榜,哪家好?哪家靠谱?选哪家? - AIEO
  • 2025年口碑好的医用冷冻冷藏防爆冰箱生产商推荐,靠谱化学品 - 工业推荐榜
  • 2025 最新国内电子签名排行:国内电子签名软件哪家强? - 博客万
  • 常熟国强和茂管材有限公司的产品质量怎样?售后服务如何? - 工业品牌热点
  • 信号与系统 于慧敏 抽样函数
  • 考研论文引用格式 AI 校验实操:工具合集 + 便捷的技术原理
  • 考研论文引用格式 AI 校验实操:工具合集 + 便捷的技术原理
  • 北京财产分割服务律所排名 2026专业能力与胜诉率测评 - 老周说教育
  • 2025 年企业智能 BI 私有化部署厂商选择指南:BI 私有化部署方案商如何赋能企业数据价值释放 - 品牌2026
  • 深圳GEO优化公司全景解析:技术标杆与选型指南 - 品牌评测官
  • A5纸打印电子发票
  • 梦境文本转换器
  • css-display
  • 2025本地回弹仪销售实力厂家排行榜及联系方式,一体式数显回弹仪/混凝土回弹仪/红外分光光度计/涂层测厚仪/楼板测厚仪回弹仪厂家口碑排行 - 品牌推荐师
  • 境外上市辅导机构观察:顺安资本及多家美股上市辅导机构与中国境外券商投行机构的实践 - AIEO
  • 2025年12月精馏塔优质头部实力生产厂家:精馏装置,不锈钢精馏塔,玻璃精馏塔,实验室精馏塔推荐知名品牌 - 品牌推荐大师1
  • 2025年行业内比较好的智能货架源头厂家哪家好,贯通货架/立体货架/可调节货架/流利式货架/牛脚式货架/智能货架厂商口碑推荐榜 - 品牌推荐师
  • 浙中婚拍标杆,品质影像铸经典|义乌市罗亚摄影有限公司品牌官宣 - charlieruizvin
  • 浙中婚拍标杆,品质影像铸经典|义乌市罗亚摄影有限公司品牌官宣 - charlieruizvin