Facebook
From amit, 3 Years ago, written in C.
Embed
Download Paste or View Raw
Hits: 284
  1. #define MAX_SIZE 100
  2.  
  3.  
  4. struct buffer_element {
  5. }
  6.  
  7. struct ring_buffer {
  8.         int consumer_ind;
  9.         int producer_ind;
  10.         buffer_element elements[MAX_SIZE];
  11. }
  12.  
  13. struct ring_buffer buf;
  14. buf.consumer_ind = 0
  15. buf.producer_ind = 0
  16.  
  17. //rw_lock my_lock;
  18.  
  19. int write(buffer_element *element) {
  20.         if (buf.producer_ind == (buf.consumer_ind - 1) % MAX_SIZE) {
  21.                 return -1
  22.         }
  23.  
  24.         memcpy(&buf.elements[buf.producer_ind], element, sizeof(buffer_element))
  25.         buf.producer_ind = buf.producer_ind == MAX_SIZE -1 ? 0 : buf.producer_ind + 1;
  26.  
  27.         return 0;
  28. }
  29.  
  30.  
  31. int read(buffer_element *element) {
  32.         if (buf.producer_ind == buf.consumer_ind) {
  33.                 // no data
  34.                 return -1;
  35.         }
  36.         memcpy(element, &buf.elements[buf.consumer_ind], sizeof(buffer_element))
  37.         buf.consumer_ind = buf.consumer_ind == MAX_SIZE -1 ? 0 : buf.consumer_ind + 1;
  38.         return 0;
  39. }