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

查看:123
本文介绍了如何实现在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 were 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.

其实我很高兴地绕过任何的原始速度标准库的 - 从我所见过的code的,它没有大量的CPU进行了优化:它看起来像他们刚刚编译C code表示如 strcpy的东西()和这样的,没有手工codeD组装。

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.

任意code或想法将不胜AP preciated。所需的操作是:

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


  • 创建具有特定大小的缓冲区。

  • 在尾摆。

  • 从头部
  • 得到。

  • 返回计数。

  • 删除缓冲区。

推荐答案

可以列举的时候,你code建立缓冲区所需要的类型,或者你需要能够通过动态运行时添加的类型电话?如果是前者,那么我会创建缓冲区为n结构的堆分配数组,其中每个结构包含两个要素:一个枚举标签识别的数据类型,所有的数据类型的联合。你在为小单元的额外存储方面失去什么,你弥补没有处理分配/释放和由此产生内存碎片的条款。然后你只需要跟踪定义缓冲区的头部和尾部的元素开始和结束的指标,并确保递增/递减指标时,计算模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天全站免登陆