你如何在 C 中实现循环缓冲区? [英] How do you implement a circular buffer in C?

查看:23
本文介绍了你如何在 C 中实现循环缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个固定大小(在创建时可以在运行时选择,而不是在编译时选择)循环缓冲区,它可以容纳任何类型的对象,并且需要非常表现.我认为不会出现资源争用问题,因为虽然它是在一个多任务嵌入式环境中,但它是一个协作环境,因此任务本身可以管理它.

I have a need for a fixed-size (selectable at run-time when creating it, not compile-time) circular buffer which can hold objects of any type and it needs to be very high performance. I don't think there will be resource contention issues since, although it's in a multi-tasking embedded environment, it's a co-operative one so the tasks themselves can manage that.

我最初的想法是在缓冲区中存储一个简单的结构,该结构将包含类型(简单枚举/定义)和一个指向有效负载的空指针,但我希望它尽可能快,所以我愿意接受建议这涉及绕过堆.

My initial thought was to store a simple struct in the buffer which would contain the type (simple enum/define) and a void pointer to the payload but I want this to be as fast as possible so I'm open to suggestions that involve bypassing the heap.

实际上,我很高兴绕过任何标准库以提高原始速度 - 从我所看到的代码来看,它并没有针对 CPU 进行大量优化:看起来他们只是为诸如 strcpy() 等等,没有手工编码的程序集.

Actually I'm happy to bypass any of the standard library for raw speed - from what I've seen of the code, it's not heavily optimized for the CPU : it looks like they just compiled C code for things like strcpy() and such, there's no hand-coded assembly.

任何代码或想法将不胜感激.所需的操作是:

Any code or ideas would be greatly appreciated. The operations required are:

  • 创建具有特定大小的缓冲区.
  • 放在尾部.
  • 从头开始.
  • 返回计数.
  • 删除缓冲区.

推荐答案

您能否在对缓冲区进行编码时枚举所需的类型,或者您是否需要能够在运行时通过动态调用添加类型?如果是前者,那么我会将缓冲区创建为 n 个结构体的堆分配数组,其中每个结构体由两个元素组成:标识数据类型的枚举标记和所有数据类型的联合.您在小元素的额外存储方面损失了什么,您可以通过不必处理分配/解除分配以及由此产生的内存碎片来弥补.然后您只需要跟踪定义缓冲区的头和尾元素的开始和结束索引,并确保在增加/减少索引时计算 mod n.

Can you enumerate the types needed at the time you code up the buffer, or do you need to be able to add types at run time via dynamic calls? If the former, then I would create the buffer as a heap-allocated array of n structs, where each struct consists of two elements: an enum tag identifying the data type, and a union of all the data types. What you lose in terms of extra storage for small elements, you make up in terms of not having to deal with allocation/deallocation and the resulting memory fragmentation. Then you just need to keep track of the start and end indices that define the head and tail elements of the buffer, and make sure to compute mod n when incrementing/decrementing the indices.

这篇关于你如何在 C 中实现循环缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆