Home / Learn Embedded C / Semaphores Explained

Semaphores Explained

A counting synchronization primitive used for signaling between tasks (or between an ISR and a task).

In shortA counting synchronization primitive used for signaling between tasks (or between an ISR and a task).

What's actually going on

Mutex vs semaphoreMutexStrict ownership: one task ata timeProtects one specific sharedresourceSemaphoreA count; signals events oravailabilityGreat for ISR-to-tasksignaling
Mutex vs semaphore

Definition

A semaphore holds a count and supports two operations: "give" (increments the count, signaling availability or an event) and "take" (decrements the count, blocking if it is already zero) — commonly used to signal "an event happened" between an ISR and a task, or to limit concurrent access to a pool of N resources.

Why you need this

Unlike a mutex (strictly one owner at a time, tightly tied to protecting one resource), a semaphore is a more general signaling tool — "a byte arrived" (binary semaphore, count of 0 or 1) or "there are 3 free buffer slots" (counting semaphore) are both natural semaphore use cases.

How it works

A binary semaphore (count capped at 0 or 1) is often used specifically for ISR-to-task signaling: the ISR "gives" the semaphore quickly (keeping the ISR short, per the Interrupts group) and a waiting task's "take" call unblocks to do the real processing.

Where you'll see this

  • ISR-to-task signaling
  • Resource-pool availability tracking
  • Event-driven task design

Try it

A simulated binary semaphore: an "ISR" gives it, a "task" takes itC: edit and run

The ISR's "give" is kept trivially short; the real processing happens afterward in the task that "took" the semaphore.

Try it: a counting semaphore guarding a pool of buffers

Tracking 3 free buffer slots with a counting semaphoreC: edit and run

Unlike a binary semaphore, this counting semaphore tracks how many of several identical resources are currently available.

Test what you just read

1. What is a classic use of a binary semaphore in interrupt-driven firmware?