ring_buf_test.c 1.3 KB

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