C / raylib
Advanced
C11 stdatomic / C99
멀티스레드 오디오 및 통신을 위한 고성능 C 언어 락프리 원형 큐(Lock-Free Ring Buffer)
단일 생산자-단일 소비자(SPSC) 환경에서 뮤텍스 락(Mutex) 없이 원자적 메모리 배리어로 스레드 안전성과 제로 레이턴시를 달성하는 링 버퍼 구현.
#C #LockFree #Concurrency #RingBuffer #Audio
핵심 개념실시간 오디오 콜백이나 고속 통신 스레드에서
pthread_mutex_lock을 걸면 우선순위 역전(Priority Inversion)으로 오디오 틱 잡음이나 지연이 생깁니다. 2의 거듭제곱 크기 버퍼와 비트마스크 AND 연산, 원자적 인덱스 갱신을 활용하면 락 없이 완벽히 스레드 세이프합니다.1. SPSC 락프리 링 버퍼 C 구현
#include <stdbool.h>
#include <stdint.h>
#define BUFFER_SIZE 1024 // 2의 거듭제곱 필수
#define BUFFER_MASK (BUFFER_SIZE - 1)
typedef struct {
uint8_t data[BUFFER_SIZE];
volatile uint32_t head; // 생산자가 기록
volatile uint32_t tail; // 소비자가 읽음
} RingBuffer;
bool RingBuffer_Push(RingBuffer* rb, uint8_t byte) {
uint32_t head = rb->head;
uint32_t next_head = (head + 1) & BUFFER_MASK;
if (next_head == rb->tail) return false; // 버퍼 가득 참 (Full)
rb->data[head] = byte;
rb->head = next_head;
return true;
}
bool RingBuffer_Pop(RingBuffer* rb, uint8_t* byte) {
uint32_t tail = rb->tail;
if (tail == rb->head) return false; // 버퍼 비어있음 (Empty)
*byte = rb->data[tail];
rb->tail = (tail + 1) & BUFFER_MASK;
return true;
}