C LANGUAGE
ring buffer
circular buffer
Author: CrazyMonkey
email: kccddb@gmail.com
Date: 20220726
Copyright: CC BY-NC-SA
Learn More →
另一重要的 circular buffer 運用, 尤其是記憶體受限時, 例如 單晶片, embedded system 或資料變動快速與大量時(使用circular buffer 不需要 經常 malloc, free, 如此可減少 OS 進行garbage collection! )
Learn More →
Reference source code
cring.h
typedef struct _ring_buffer
{
void *buffer; // data buffer
void *buffer_end; // end of data buffer
size_t capacity; // maximum number of items in the buffer
size_t count; // number of items in the buffer
size_t sz; // size of each item in the buffer
void *head; // pointer to head
void *tail; // pointer to tail
int (*push)(struct _ring_buffer *pthis,const void *item);
int (*pop)(struct _ring_buffer *ring, void *item);
} ring_buffer;
/*
byte acces
ring_init( size_t capacity, 1);
*/
ring_buffer * ring_init( size_t capacity, size_t sz);
void ring_exit(ring_buffer *ring);
cring.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include "cring.h"
static int ring_push(ring_buffer *ring, const void *item)
{
if(ring->count == ring->capacity){
return 0;
}
memcpy(ring->head, item, ring->sz);
ring->head = (unsigned char*)ring->head + ring->sz;
if(ring->head == ring->buffer_end)
ring->head = ring->buffer;
ring->count++;
return ring->count;
}
static int ring_pop(ring_buffer *ring, void *item)
{
if(ring->count == 0){
// handle error
return 0;
}
memcpy(item, ring->tail, ring->sz);
ring->tail = (unsigned char*)ring->tail + ring->sz;
if(ring->tail == ring->buffer_end)
ring->tail = ring->buffer;
ring->count--;
return ring->count;
}
ring_buffer * ring_init( size_t capacity, size_t sz)
{
ring_buffer *ring;
ring=malloc(sizeof(ring_buffer));
if(ring==NULL)return NULL;
ring->buffer = malloc(capacity * sz);
if(ring->buffer == NULL){
free(ring);
return NULL;
}
ring->buffer_end = (unsigned char *)ring->buffer + capacity * sz;
ring->capacity = capacity;
ring->count = 0;
ring->sz = sz;
ring->head = ring->buffer;
ring->tail = ring->buffer;
ring->push=ring_push;
ring->pop=ring_pop;
}
void ring_exit(ring_buffer *ring)
{
if(ring){
free(ring->buffer);
free(ring);
}
}
HW.
Learn More →
Authors: CrazyDog, CrazyMonkeyemail: kccddb@gmail.comDate: 20230222
Mar 14, 2025Author: \mathcal{CrazyDog}, Ph.D. in Electrical Engineering, NCTUemail: kccddb@gmail.comDate: 20230910
Nov 4, 2024Author: WhoAmI Date: 20230523 email:kccddb@gmail.com Copyright: CC BY-NC-SA 《荀子‧勸學》不積跬步,無以至千里;不積小流,無以成江海。 I. Mutex variables MUST be declared with type pthread_mutex_t, and must be initialized before they can be used. II. 了解 pthread_mutex_lock / pthread_mutex_unlock 與可能問題和代價 III. 程式執行效率與startvation 等問題
Jul 11, 2024Author: WhoAmIemail: kccddb@gmail.com
Dec 6, 2023or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up