| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- // 环形队列测试, 单生产者单消费者时线程安全
- #include <stdio.h>
- #include <stdint.h>
- #include <stdbool.h>
- #include "ring_buf.h"
- // 回调函数示例,用于 RingBuf_process_all
- void print_element(RingBufElement el) {
- printf("Processed element: %u\n", el);
- }
- int main(void)
- {
- RingBufElement storage[8];
- RingBuf myRing;
- // 1. 初始化环形缓冲区
- RingBuf_ctor(&myRing, storage, sizeof(storage) / sizeof(RingBufElement));
- // 2. 向环形缓冲区写入
- for(uint8_t i = 1; i <= 5; ++i) {
- if (RingBuf_put(&myRing, i)) {
- printf("Put element: %u\n", i);
- } else {
- printf("Buffer full, failed to put: %u\n", i);
- }
- }
- // 3. 检查剩余可用空间
- RingBufCtr free_slots = RingBuf_num_free(&myRing);
- printf("Number of free slots: %u\n", free_slots);
- // 4. 从环形缓冲区取出
- RingBufElement val;
- if(RingBuf_get(&myRing, &val)) {
- printf("Got element: %u\n", val);
- } else {
- printf("Buffer empty, cannot get element\n");
- }
- // 5. 遍历处理剩余元素
- printf("Processing all remaining elements:\n");
- RingBuf_process_all(&myRing, print_element);
- // 6. 检查缓冲区的状态
- free_slots = RingBuf_num_free(&myRing);
- printf("Number of free slots after processing: %u\n", free_slots);
- return 0;
- }
|