C 语言的 2D 环形缓冲区
我编写了一个简单的环形缓冲区,其环形大小为 5,用于存储 A 类型的值。 现在我必须扩展这个缓冲区来存储 B 类型值(也是 5 个值)。
为了给出一个概述,我将读取索引和写入索引的变量定义为全局易失性,以及两个用于在环形缓冲区上读取和写入的函数。
我只需要做:ring data = int read_ring_data() 和 write_ring_data(int pass_new_data)
易失性全局变量有助于控制读取和写入的位置。
我的问题是,有没有办法重用这些读写函数,通过简单地重新调整尺寸来将其扩展到 2D 缓冲区?我该如何实施?
I have coded a simple ring buffer which has a ring size of 5 to store values of type A.
Now I have to extend this buffer to store type B values(also 5 values).
To give an overview, I have defined the variables for read index and write index as global volatile and two functions for reading and writing on the ring buffer.
I only have to do : ring data = int read_ring_data()
and write_ring_data(int pass_new_data)
The volatile global variables help control the locations of read and write.
My question is, is there a way to reuse these read and write functions for extending it to a 2D buffer by simply re-dimensioning it? How do I implement it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您仍然可以在 C 中以面向对象的风格进行编码,只需使用结构作为类,而“方法”只是采用指向类的指针的函数。我将在 C 中创建一个通用的“ring-buffer”“类”,如下所示。
当然,您必须负责分配 RingBuffer 结构,如果有些人采用一致的命名方案,他们可能会使用某些宏来做到这一点对于“init”(相当于c++构造函数)和“shutdown”/“release”函数
当然有很多排列..制作一个环形缓冲区非常容易,您可以在其中读/写可变大小的元素,也许可以写每个点进入缓冲区的元素大小。当然也可以动态调整大小,甚至更改元素大小。
尽管 C 语言对创建数据结构的语言支持比 C++ 更为原始,但有时重新处理问题以使用简单的数据结构可以带来性能优势。此外,将数据结构视为简单的内存块(大小作为参数传递)可能会导致编译器内联减少:紧凑的代码作为在内部循环之外使用的默认方法(i-cache 一致性)具有优势。
可以将“缓冲区标头”结构和数组数据组合到一个分配中(假设缓冲区数据遵循内存中的标头结构),这减少了指针取消引用的数量。
You can still code in an object oriented style in C , simply using struct's as classes, and 'methods' are just functions that take a pointer to a class. I would create a general purpose 'ring-buffer' 'class' in C as follows..
you'd have to take care of allocating the RingBuffer structs of course, some people might do that with some macro if they adopt a consistent naming scheme for 'init'(equiv of c++ constructor) and 'shutdown'/'release' functions
Of course there are many permutations.. it would be very easy to make a ring buffer into which you can read/write variable sized elements, perhaps writing the element size into the buffer at each point. it would certainly be possible to resize on the fly aswell, even change the element size.
Although the language support for creating data structures is more primitive in C than in C++, sometimes re-working a problem to use simple data structures can have performance benefits. Also treating data structures as simple blocks of memory with size passed as a parameter may cause less compiler inlining: compact code can have advantages as the default method to use outside of inner loops (i-cache coherency).
it would be possible to combine the 'Buffer Header' structure and the array data into one allocation, (just assume the buffer data follows the header structure in memory), which reduces the amount of pointer-dereferencing going on.