Skip to content

Day58 - POSIX Semaphore Synchronization

Date

2026-05-19


Topics

  • POSIX named semaphore
  • counting semaphore
  • binary semaphore
  • sem_trywait()
  • sem_timedwait()
  • shared memory synchronization
  • producer / consumer queue
  • ring buffer
  • process-shared pthread mutex

Implemented

Basic Semaphore

Implemented:

  • sem_open()
  • sem_wait()
  • sem_post()
  • sem_close()
  • sem_unlink()

Created:

  • waiter
  • poster
  • cleanup

Non-blocking / Timeout Wait

Implemented:

  • sem_trywait()
  • sem_timedwait()

Learned:

  • EAGAIN
  • ETIMEDOUT
  • EINTR handling

Shared Memory IPC

Implemented:

  • shared memory producer
  • shared memory consumer
  • semaphore synchronization

Architecture:

shared memory
    = data plane

semaphore
    = synchronization plane

Ring Buffer Queue

Converted single-slot shared memory into:

shared ring buffer queue

Added:

  • head
  • tail
  • count
  • next_seq

Implemented:

  • shm_ring_write()
  • shm_ring_read()

Bounded Producer / Consumer Queue

Implemented:

  • filled semaphore
  • empty semaphore
  • queue synchronization

Learned:

filled semaphore
    = readable item count

empty semaphore
    = writable slot count

Process-shared pthread mutex

Implemented:

PTHREAD_PROCESS_SHARED

Used mutex to protect:

  • head/tail update
  • ring consistency
  • queue metadata

Important Concepts

Semaphore != Mutex

Semaphore:

  • synchronization
  • resource counting

Mutex:

  • ownership
  • critical section protection

Queue state != Synchronization state

Queue state:

  • head
  • tail
  • count

Synchronization state:

  • semaphore count

Result

Successfully implemented:

shared memory
+
ring buffer
+
counting semaphore
+
process-shared mutex
+
producer-consumer synchronization

This architecture is similar to:

  • RTOS queue system
  • Linux middleware queue
  • IPC daemon queue
  • packet processing pipeline

```