C / raylib
Advanced
C11 stdatomic / C99
멀티스레드 오디오 및 통신을 위한 고성능 C 언어 락프리 원형 큐(Lock-Free Ring Buffer)High-Performance C Lock-Free Ring Buffer for Multithreaded Audio and I/O
단일 생산자-단일 소비자(SPSC) 환경에서 뮤텍스 락(Mutex) 없이 원자적 인덱스 연산으로 스레드 안전성과 낮은 지연 시간을 확보하는 링 버퍼 구현입니다.A Single-Producer Single-Consumer (SPSC) lock-free circular queue in C11 using atomic acquire-release memory ordering and power-of-two bitmasking for low-latency thread communication.
#C #LockFree #Concurrency #RingBuffer #Audio
핵심 개념실시간 오디오 콜백이나 고속 시리얼 통신 스레드에서
pthread_mutex_lock을 호출하면 컨텍스트 스위칭과 우선순위 역전(Priority Inversion)으로 인해 오디오 틱 잡음이나 패킷 누락이 발생할 수 있습니다. 2의 거듭제곱 크기 버퍼와 비트마스크 AND 연산, 그리고 단일 생산자·단일 소비자(SPSC) 인덱스 분리를 활용하면 뮤텍스 없이 일관된 스레드 안전성을 확보할 수 있습니다.Key ConceptAcquiring a mutex (
pthread_mutex_lock) inside a real-time audio callback or high-speed serial thread risks context switches and priority inversion, leading to audio dropouts or missed packets. By combining a power-of-two buffer size, bitwise AND masking, and strict Single-Producer Single-Consumer (SPSC) index ownership, threads can exchange data safely without locks.1. SPSC 락프리 링 버퍼 C 구현1. SPSC Lock-Free Ring Buffer Implementation in C11
#include <stdbool.h>
#include <stdint.h>
#include <stdatomic.h>
#define BUFFER_SIZE 1024 // 2의 거듭제곱 필수
#define BUFFER_MASK (BUFFER_SIZE - 1)
typedef struct {
uint8_t data[BUFFER_SIZE];
atomic_uint head; // 생산자(Producer)만 수정
atomic_uint tail; // 소비자(Consumer)만 수정
} RingBuffer;
bool RingBuffer_Push(RingBuffer *rb, uint8_t byte) {
uint32_t head = atomic_load_explicit(&rb->head, memory_order_relaxed);
uint32_t next_head = (head + 1) & BUFFER_MASK;
// 소비자가 갱신한 tail을 acquire 배리어로 읽음
if (next_head == atomic_load_explicit(&rb->tail, memory_order_acquire)) {
return false; // 버퍼 가득 참 (Full)
}
rb->data[head] = byte;
// 데이터 기록 완료 후 head 갱신을 release 배리어로 게시
atomic_store_explicit(&rb->head, next_head, memory_order_release);
return true;
}
bool RingBuffer_Pop(RingBuffer *rb, uint8_t *byte) {
uint32_t tail = atomic_load_explicit(&rb->tail, memory_order_relaxed);
// 생산자가 갱신한 head를 acquire 배리어로 읽음
if (tail == atomic_load_explicit(&rb->head, memory_order_acquire)) {
return false; // 버퍼 비어있음 (Empty)
}
*byte = rb->data[tail];
atomic_store_explicit(&rb->tail, (tail + 1) & BUFFER_MASK, memory_order_release);
return true;
}
#include <stdbool.h>
#include <stdint.h>
#include <stdatomic.h>
#define BUFFER_SIZE 1024 // Must be a power of two
#define BUFFER_MASK (BUFFER_SIZE - 1)
typedef struct {
uint8_t data[BUFFER_SIZE];
atomic_uint head; // Modified exclusively by Producer
atomic_uint tail; // Modified exclusively by Consumer
} RingBuffer;
bool RingBuffer_Push(RingBuffer *rb, uint8_t byte) {
uint32_t head = atomic_load_explicit(&rb->head, memory_order_relaxed);
uint32_t next_head = (head + 1) & BUFFER_MASK;
// Read consumer-updated tail with acquire semantics
if (next_head == atomic_load_explicit(&rb->tail, memory_order_acquire)) {
return false; // Buffer Full
}
rb->data[head] = byte;
// Publish updated head with release semantics after writing payload
atomic_store_explicit(&rb->head, next_head, memory_order_release);
return true;
}
bool RingBuffer_Pop(RingBuffer *rb, uint8_t *byte) {
uint32_t tail = atomic_load_explicit(&rb->tail, memory_order_relaxed);
// Read producer-updated head with acquire semantics
if (tail == atomic_load_explicit(&rb->head, memory_order_acquire)) {
return false; // Buffer Empty
}
*byte = rb->data[tail];
atomic_store_explicit(&rb->tail, (tail + 1) & BUFFER_MASK, memory_order_release);
return true;
}
2. 실무 적용 및 주의사항2. Practical Considerations and Caveats
- SPSC(단일 생산자-단일 소비자) 전제 조건 준수: 위 알고리즘은
head를 오직 하나의 생산자 스레드만 수정하고,tail을 오직 하나의 소비자 스레드만 수정한다는 가정 하에 동작합니다. 다중 생산자(MPMC) 환경에서는atomic_compare_exchange_weak기반 CAS 루프나 뮤텍스가 필요합니다. volatile대신 C11 메모리 배리어(acquire/release) 사용: C 언어의volatile키워드는 컴파일러 최적화만 억제할 뿐 ARM이나 멀티코어 CPU의 하드웨어 명령어 재배치(Out-of-Order Execution)를 막지 못합니다.rb->data[head] = byte기록이rb->head갱신보다 먼저 타 코어에 보이도록memory_order_release와memory_order_acquire를 명시해야 합니다.- 2의 거듭제곱 버퍼 크기 강제:
BUFFER_SIZE를 512, 1024, 4096 같은 $2^n$으로 지정하면 느린 정수 나눗셈(% BUFFER_SIZE)을 단일 클럭 비트 연산(& (BUFFER_SIZE - 1))으로 대체할 수 있습니다.
- Strict SPSC (Single-Producer Single-Consumer) Requirement: This lock-free design assumes exactly one thread writes to
headand one thread writes totail. Multi-producer or multi-consumer (MPMC) scenarios require Compare-And-Swap (atomic_compare_exchange_weak) loops or locks. - Use C11 Acquire/Release Atomics Instead of
volatile: Thevolatilekeyword only prevents compiler register caching and does not prevent hardware memory reordering on ARM or RISC-V CPUs. Pairingmemory_order_releasewithmemory_order_acquireguarantees thatrb->data[head]is visible in memory before the updatedheadindex is observed. - Power-of-Two Buffer Capacity: Restricting
BUFFER_SIZEto $2^n$ (e.g., 512, 1024, 4096) replaces division-based modulo (% BUFFER_SIZE) with a single-cycle bitwise AND (& (BUFFER_SIZE - 1)).
원자적 Acquire-Release 메모리 순서와 2의 거듭제곱 마스킹을 결합한 SPSC 링 버퍼는 오디오 DSP 스레드와 메인 게임 루프 사이의 실시간 데이터 스트리밍에 적합한 구조입니다.
An SPSC ring buffer built with C11 acquire-release atomics and bitmask indexing provides deterministic, wait-free data streaming between real-time audio callbacks and main application threads.