ring_buf_test.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // 环形队列测试, 单生产者单消费者时线程安全
  2. #include <stdio.h>
  3. #include <stdint.h>
  4. #include <stdbool.h>
  5. #include "ring_buf.h"
  6. // 回调函数示例,用于 RingBuf_process_all
  7. void print_element(RingBufElement el) {
  8. printf("Processed element: %u\n", el);
  9. }
  10. int main(void)
  11. {
  12. RingBufElement storage[8];
  13. RingBuf myRing;
  14. // 1. 初始化环形缓冲区
  15. RingBuf_ctor(&myRing, storage, sizeof(storage) / sizeof(RingBufElement));
  16. // 2. 向环形缓冲区写入
  17. for(uint8_t i = 1; i <= 5; ++i) {
  18. if (RingBuf_put(&myRing, i)) {
  19. printf("Put element: %u\n", i);
  20. } else {
  21. printf("Buffer full, failed to put: %u\n", i);
  22. }
  23. }
  24. // 3. 检查剩余可用空间
  25. RingBufCtr free_slots = RingBuf_num_free(&myRing);
  26. printf("Number of free slots: %u\n", free_slots);
  27. // 4. 从环形缓冲区取出
  28. RingBufElement val;
  29. if(RingBuf_get(&myRing, &val)) {
  30. printf("Got element: %u\n", val);
  31. } else {
  32. printf("Buffer empty, cannot get element\n");
  33. }
  34. // 5. 遍历处理剩余元素
  35. printf("Processing all remaining elements:\n");
  36. RingBuf_process_all(&myRing, print_element);
  37. // 6. 检查缓冲区的状态
  38. free_slots = RingBuf_num_free(&myRing);
  39. printf("Number of free slots after processing: %u\n", free_slots);
  40. return 0;
  41. }