ring_buffer.h 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. #ifndef RING_BUFFER_H
  2. #define RING_BUFFER_H
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <pthread.h>
  6. #define CACHE_LINE_SIZE 64
  7. #define MAX_DATA_LENGTH 32768 // 32kb; try to stay in L1 cache
  8. typedef struct {
  9. size_t total_length;
  10. size_t fragment_offset;
  11. char *data; // Use pointer to avoid copying data
  12. } __attribute__((aligned(CACHE_LINE_SIZE))) RingBufferSlot;
  13. typedef struct {
  14. RingBufferSlot *slots;
  15. size_t write_index;
  16. size_t read_index;
  17. size_t size;
  18. pthread_mutex_t mutex;
  19. pthread_cond_t cond;
  20. } RingBuffer;
  21. void ring_buffer_init(RingBuffer *ring_buffer, RingBufferSlot *slots, size_t size);
  22. void ring_buffer_destroy(RingBuffer *ring_buffer);
  23. size_t ring_buffer_write(RingBuffer *ring_buffer, const void *data, size_t data_length);
  24. RingBufferSlot* ring_buffer_get_read_slot(RingBuffer *ring_buffer);
  25. void ring_buffer_advance_read_index(RingBuffer *ring_buffer);
  26. void ring_buffer_wait_for_signal(RingBuffer *ring_buffer);
  27. int is_slot_unread(RingBuffer *ring_buffer, size_t index);
  28. void ring_buffer_write_full(RingBuffer *ring_buffer, const void *data, size_t data_length);
  29. #endif