当前位置: 首页 > 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.gsyq.cn/news/81335.html

相关文章:

  • 2025 年 BI 本地私有化部署厂商全景图:企业智能 BI 私有化部署厂商提供的一站式智能 BI 本地化服务指南 - 品牌2026
  • 2025年琉璃瓦厂家推荐排行榜,哪家好?哪家靠谱?选哪家? - AIEO
  • 2025年口碑好的医用冷冻冷藏防爆冰箱生产商推荐,靠谱化学品 - 工业推荐榜
  • 2025 最新国内电子签名排行:国内电子签名软件哪家强? - 博客万
  • 常熟国强和茂管材有限公司的产品质量怎样?售后服务如何? - 工业品牌热点
  • 考研论文引用格式 AI 校验实操:工具合集 + 便捷的技术原理
  • 2025 年企业智能 BI 私有化部署厂商选择指南:BI 私有化部署方案商如何赋能企业数据价值释放 - 品牌2026
  • 深圳GEO优化公司全景解析:技术标杆与选型指南 - 品牌评测官
  • A5纸打印电子发票
  • 2025本地回弹仪销售实力厂家排行榜及联系方式,一体式数显回弹仪/混凝土回弹仪/红外分光光度计/涂层测厚仪/楼板测厚仪回弹仪厂家口碑排行 - 品牌推荐师
  • 2025年行业内比较好的智能货架源头厂家哪家好,贯通货架/立体货架/可调节货架/流利式货架/牛脚式货架/智能货架厂商口碑推荐榜 - 品牌推荐师
  • 2025晶体炉生产厂TOP5权威推荐:深度测评指南,甄选企业 - mypinpai
  • 2025年五大脚垫式防爆包装封口机生产商推荐:看哪家信誉好 - myqiye
  • 软件官网UX自查清单|兰亭妙微10年经验总结,避坑必藏
  • 2025年检测仪行业领军企业,官方联系电话独家汇总,钢筋位置测定仪/一体式语音数显回弹仪/楼板测厚仪/混凝土回弹仪/钢砧检测仪源头厂家找哪家 - 品牌推荐师
  • 详细介绍:MongoDB知识点与技巧总结
  • 2025年隔音房源头厂家实力推荐,看看哪家工艺水平高? - 工业推荐榜
  • 深入解析:ELK Stack核心原理与运用要点解析
  • 医疗交互的 “精准协作”:北京兰亭妙微打造的超声机器人界面革新
  • 如何选择一家靠谱的新疆旅行社?2025年年终最新市场评测与5家实力机构推荐! - 十大品牌推荐
  • 互感器综合测试仪/智能互感器伏安特性测试仪哪个品牌好?哪家好?源头厂家推荐 - 品牌推荐大师1
  • 2025年年终刷宝游戏推荐:多平台横评与实测体验,聚焦不同用户偏好的5款优质游戏选购指南 - 十大品牌推荐
  • 2025年纸托盘实力厂家推荐榜单:仓储物流托盘‌/木托盘‌/免熏蒸托盘源头厂家精选 - 品牌推荐官
  • 【节点】[Adjustment-ChannelMixer节点]原理解析与实际应用
  • 2025年年终刷宝游戏推荐:聚焦ARPG与暗黑like品类,专家严选5款优质案例可靠性横评 - 十大品牌推荐
  • 2025年12月成都排臭蹲便器/防堵卫浴/蹲便器/高端卫浴公司推荐 - 2025年11月品牌推荐榜
  • 2025年台式XAFS推荐生产厂家,台式XAFS行业标杆企业 - 品牌推荐大师
  • 2025年12月国产微波马弗炉价格对比/生产商/代理商/知名品牌/推荐品牌/供应商 - 品牌推荐大师
  • 2025年年终中国员工福利公司推荐:从技术平台到生态资源全方位评估,10家实测表现卓越的服务商聚焦 - 品牌推荐
  • 2025年农村酿酒设备五大厂家推荐:5斤/20斤酿酒设备哪个 - 工业品牌热点