</>EmbeddedInterview

What is a semaphore, and how does it differ from a mutex in POSIX? How are semaphores used for mutual exclusion and for synchronisation?

MediumOperating System Concepts

Short answer: A semaphore is an integer counter with two atomic operations: wait (P, sem_wait: decrement, block if it would go below zero) and post (V, sem_post: increment, wake a waiter). A mutex is a lock with an owner: only the thread that locked it may unlock it, and it can support priority inheritance and error checking. Use a mutex for mutual exclusion; use a semaphore for signalling between tasks or counting resources.

Pattern 1: mutual exclusion (semaphore initialised to 1)

sem_t s;
sem_init(&s, 0, 1);       /* 1 = one task may enter */

/* in each task */
sem_wait(&s);
/* critical section */
sem_post(&s);

Pattern 2: synchronisation / signalling (initialised to 0): task B must not continue until task A has finished step 1.

sem_t done;
sem_init(&done, 0, 0);    /* 0 = event has not happened yet */

/* task A */                    /* task B */
do_step1();                     sem_wait(&done);   /* blocks until A posts */
sem_post(&done);                do_step2();

Whatever order the scheduler runs them in (even on one CPU, even if B starts first), do_step2() always runs after do_step1().

Pattern 3: counting resources (initialised to N): a pool of N buffers or connections; sem_wait takes one, sem_post returns one.

Mutex vs semaphore

Mutex Semaphore
Value locked / unlocked 0..N
Ownership yes, only the owner unlocks no, any task may post
Priority inheritance yes (PTHREAD_PRIO_INHERIT) no
Recursive locking optional (PTHREAD_MUTEX_RECURSIVE) no
Can post from a signal handler/ISR no sem_post is async-signal-safe
Typical use protect shared data signal events, count resources

Why not use a binary semaphore as a mutex? No owner means no priority inheritance (priority inversion risk) and no protection against another task releasing a lock it does not hold.

POSIX details: unnamed semaphores (sem_init, can be shared between processes if placed in shared memory with pshared = 1) and named ones (sem_open("/name")). The Linux implementation is built on futexes, so an uncontended wait/post never enters the kernel.