環形緩衝區

圓形緩衝區（circular buffer），也稱作圓形佇列（circular queue），迴圈緩衝區（cyclic buffer），環形緩衝區（ring buffer），是一種用於表示一個固定尺寸、頭尾相連的緩衝區的資料結構，適合快取資料流。

用法

圓形緩衝區的一個有用特性是：當一個資料元素被用掉後，其餘資料元素不需要移動其儲存位置。相反，一個非圓形緩衝區（例如一個普通的佇列）在用掉一個資料元素後，其餘資料元素需要向前搬移。換句話說，圓形緩衝區適合實現先進先出緩衝區，而非圓形緩衝區適合後進先出緩衝區。  

圓形緩衝區適合於事先明確了緩衝區的最大容量的情形。擴充一個圓形緩衝區的容量，需要搬移其中的資料。因此一個緩衝區如果需要經常調整其容量，用連結串列實現更為合適。 
寫操作覆蓋圓形緩衝區中未被處理的資料在某些情況下是允許的。特別是在多媒體處理時。例如，音訊的生產者可以覆蓋掉音效卡尚未來得及處理的音訊資料。

圓形緩衝區工作機制

由於電腦記憶體是線性位址空間，因此圓形緩衝區需要特別的設計才可以從邏輯上實現。

總是保持一個儲存單元為空

緩衝區中總是有一個儲存單元保持未使用狀態。緩衝區最多存入個資料。如果讀寫指標指向同一位置，則緩衝區為空。如果寫指標位於讀指標的相鄰後一個位置，則緩衝區為滿。這種策略的優點是簡單、粗暴；缺點是語意上實際可存資料量與緩衝區容量不一致，測試緩衝區是否滿需要做取餘數計算。

使用資料計數

這種策略不使用顯式的寫指標，而是保持著緩衝區記憶體儲的資料的計數。因此測試緩衝區是空是滿非常簡單；對效能影響可以忽略。缺點是讀寫操作都需要修改這個儲存資料計數，對於多執行緒存取緩衝區需要並行控制。

鏡像指示位

緩衝區的長度如果是n，邏輯位址空間則為0至n-1；那麼，規定n至2n-1為鏡像邏輯位址空間。本策略規定讀寫指標的位址空間為0至2n-1，其中低半部分對應於常規的邏輯位址空間，高半部分對應於鏡像邏輯位址空間。當指標值大於等於2n時，使其折返（wrapped）到ptr-2n。使用一位表示寫指標或讀指標是否進入了虛擬的鏡像儲存區：置位表示進入，不置位表示沒進入還在基本儲存區。
在讀寫指標的值相同情況下，如果二者的指示位相同，說明緩衝區為空；如果二者的指示位不同，說明緩衝區為滿。這種方法優點是測試緩衝區滿/空很簡單；不需要做取餘數操作；讀寫執行緒可以分別設計專用演算法策略，能實現精緻的並行控制。 缺點是讀寫指標各需要額外的一位作為指示位。  
如果緩衝區長度是2的冪，則本方法可以省略鏡像指示位。如果讀寫指標的值相等，則緩衝區為空；如果讀寫指標相差n，則緩衝區為滿，這可以用條件運算式（寫指標 == (讀指標 互斥或 緩衝區長度)）來判斷。
 1 // This approach adds one bit to end and start pointers 2 // Circular buffer object 3 typedef struct { 4     int size; // maximum number of elements 5     int start; // index of oldest element 6     int end; // index at which to write new element 7     ElemType *elems; // vector of elements 8 } CircularBuffer; 9 10 void cbInit(CircularBuffer *cb, int size) {11     cb->size = size;12     cb->start = 0;13     cb->end = 0;14     cb->elems = (ElemType *)calloc(cb->size, sizeof(ElemType));15 }16 17 void cbPrint(CircularBuffer *cb) {18     printf("size = 0x%x, start = %d, end = %d\n", cb->size, cb->start, cb->end);19 }20 21 int cbIsFull(CircularBuffer *cb) {22     return cb->end == (cb->start ^ cb->size); // This inverts the most significant bit of start before comparison23 }24 25 int cbIsEmpty(CircularBuffer *cb) {26     return cb->end == cb->start;27 }28 29 int cbIncr(CircularBuffer *cb, int p) {30     return (p + 1) & (2 * cb->size - 1); // start and end pointers incrementation is done modulo 2*size31 }32 33 void cbWrite(CircularBuffer *cb, ElemType *elem) {34     cb->elems[cb->end & (cb->size - 1)] = *elem;35     if (cbIsFull(cb)) // full, overwrite moves start pointer36         cb->start = cbIncr(cb, cb->start);37     cb->end = cbIncr(cb, cb->end);38 }39 40 void cbRead(CircularBuffer *cb, ElemType *elem) {41     *elem = cb->elems[cb->start & (cb->size - 1)];42     cb->start = cbIncr(cb, cb->start);43 }

讀/寫 計數

用兩個有符號整型變數分別儲存寫入、讀出緩衝區的資料數量。其差值就是緩衝區中尚未被處理的有效資料的數量。這種方法的優點是讀執行緒、寫執行緒互不干擾；缺點是需要額外兩個變數。

記錄最後的操作

使用一位記錄最後一次操作是讀還是寫。讀寫指標值相等情況下，如果最後一次操作為寫入，那麼緩衝區是滿的；如果最後一次操作為讀出，那麼緩衝區是空。 這種策略的缺點是讀寫操作共用一個標誌位，多執行緒時需要並行控制。

POSIX最佳化實現

1 #include <sys/mman.h>  2 #include <stdlib.h>  3 #include <unistd.h>  4   5 #define report_exceptional_condition() abort ()  6   7 struct ring_buffer {  8     void *address;  9     unsigned long count_bytes; 10     unsigned long write_offset_bytes; 11     unsigned long read_offset_bytes; 12 }; 13  14 // Warning order should be at least 12 for Linux 15 void ring_buffer_create (struct ring_buffer *buffer, unsigned long order) { 16     char path[] = "/dev/shm/ring-buffer-XXXXXX"; 17     int file_descriptor; 18     void *address; 19     int status; 20     file_descriptor = mkstemp(path); 21     if (file_descriptor < 0) 22         report_exceptional_condition(); 23     status = unlink(path); 24     if (status) 25         report_exceptional_condition(); 26     buffer->count_bytes = 1UL << order; 27     buffer->write_offset_bytes = 0; 28     buffer->read_offset_bytes = 0; 29     status = ftruncate(file_descriptor, buffer->count_bytes); 30     if (status) 31         report_exceptional_condition(); 32     buffer->address = mmap (NULL, buffer->count_bytes << 1, PROT_NONE, 33                             MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); 34     if (buffer->address == MAP_FAILED) 35         report_exceptional_condition(); 36     address = 37         mmap(buffer->address, buffer->count_bytes, PROT_READ | PROT_WRITE, 38              MAP_FIXED | MAP_SHARED, file_descriptor, 0); 39     if (address != buffer->address) 40         report_exceptional_condition(); 41     address = mmap(buffer->address + buffer->count_bytes, 42                    buffer->count_bytes, PROT_READ | PROT_WRITE, 43                    MAP_FIXED | MAP_SHARED, file_descriptor, 0); 44     if (address != buffer->address + buffer->count_bytes) 45         report_exceptional_condition(); 46     status = close(file_descriptor); 47     if (status) 48         report_exceptional_condition(); 49 } 50  51 void ring_buffer_free(struct ring_buffer *buffer) { 52     int status; 53     status = munmap(buffer->address, buffer->count_bytes << 1); 54     if (status) 55         report_exceptional_condition (); 56 } 57  58 void *ring_buffer_write_address(struct ring_buffer *buffer) { 59     // void pointer arithmetic is a constraint violation. 60     return buffer->address + buffer->write_offset_bytes; 61 } 62  63 void ring_buffer_write_advance(struct ring_buffer *buffer, unsigned long count_bytes) { 64     buffer->write_offset_bytes += count_bytes; 65 } 66  67 void *ring_buffer_read_address(struct ring_buffer *buffer) { 68     return buffer->address + buffer->read_offset_bytes; 69 } 70  71 void ring_buffer_read_advance(struct ring_buffer *buffer, unsigned long count_bytes) { 72     buffer->read_offset_bytes += count_bytes; 73     if (buffer->read_offset_bytes >= buffer->count_bytes) { 74         // 如果读指针大于等于缓冲区长度，那些读写指针同时折返回[0, buffer_size]范围内 75         buffer->read_offset_bytes -= buffer->count_bytes; 76         buffer->write_offset_bytes -= buffer->count_bytes; 77     } 78 } 79  80 unsigned long ring_buffer_count_bytes(struct ring_buffer *buffer) { 81     return buffer->write_offset_bytes - buffer->read_offset_bytes; 82 } 83  84 unsigned long ring_buffer_count_free_bytes(struct ring_buffer *buffer) { 85     return buffer->count_bytes - ring_buffer_count_bytes (buffer); 86 } 87  88 void ring_buffer_clear(struct ring_buffer *buffer) { 89     buffer->write_offset_bytes = 0; 90     buffer->read_offset_bytes = 0; 91 } 92  93 /*  Note, that initial anonymous mmap() can be avoided - after initial mmap() for descriptor fd, 94     you can try mmap() with hinted address as (buffer->address + buffer->count_bytes) and if it fails - 95     another one with hinted address as (buffer->address - buffer->count_bytes). 96     Make sure MAP_FIXED is not used in such case, as under certain situations it could end with segfault. 97     The advantage of such approach is, that it avoids requirement to map twice the amount you need initially 98     (especially useful e.g. if you want to use hugetlbfs and the allowed amount is limited) 99     and in context of gcc/glibc - you can avoid certain feature macros100     (MAP_ANONYMOUS usually requires one of: _BSD_SOURCE, _SVID_SOURCE or _GNU_SOURCE). */