以前在项目里用过Ring Buffer,比如用来在中断里存储UART传输的数据,然后在周期任务中再读取数据进行处理。
读取操作和存储操作是独立的,互相不影响。通过游标来表示需要读取和存储数据的位置。
这个功能用C写就是个结构体加操作函数,用C++用一个类就可以。
以前用过的版本还要找一下,网上搜一艘看有没有合适的,现在手头上需要用一下。
cnoviello (Carmine Noviello) · GitHub
这个项目也是十年前的了,不过也是够用了,网上搜下来看,就这个我觉得还行。
A ring buffer, also known as a circular buffer or circular queue, is a data structure that uses a fixed-size buffer as if it were connected end-to-end, allowing efficient storage and retrieval of data in a first-in, first-out (FIFO) manner.
Here's a more detailed explanation:
Circular Structure:
The key characteristic is that the last element in the buffer is connected to the first, creating a circular appearance.
Fixed Size:
Ring buffers have a predefined size, meaning they don't dynamically resize like some other data structures.
FIFO Behavior:
Data is added (written) and removed (read) from the buffer in a FIFO manner, meaning the first element added is the first element removed.
Efficiency:
Ring buffers are efficient because they avoid the need to shift elements when data is added or removed, which can be time-consuming with standard arrays.
Applications:
Ring buffers are commonly used in situations where data needs to be buffered between different processes or threads, such as in audio/video streaming, network interfaces, and data logging.
Overwriting:
When the buffer is full, new data overwrites the oldest data, ensuring that the buffer always contains the most recent information.
Examples:
- Network Interface Cards (NICs): Ring buffers store incoming packets until the device driver can process them.
- Audio/Video Streaming: Ring buffers can store audio/video data packets for smooth playback.
Data Logging: Ring buffers can store recent log messages, allowing for efficient retrieval of the latest events. - Embedded Systems: Due to their fixed size and efficiency, ring buffers are often used in resource-constrained embedded systems.