Lesson 12 of 15

Semaphore

The Semaphore

A semaphore is a synchronization primitive used throughout the Linux kernel — for protecting shared resources, signalling between processes, and limiting concurrency.

A counting semaphore has an integer value:

  • sem_down (also called P or wait): decrement the value. If it was already 0, the caller blocks — it waits until another process calls sem_up.
  • sem_up (also called V or signal): increment the value. If any processes are blocked, wake one of them.
typedef struct { int value; } Semaphore;

// Returns 1 if acquired, 0 if would block
int sem_down(Semaphore *s) {
    if (s->value > 0) { s->value--; return 1; }
    return 0;
}

void sem_up(Semaphore *s) { s->value++; }

Since we cannot actually block in our simulation, sem_down returns 1 if it acquired the semaphore, or 0 if it would have blocked.

Binary vs Counting Semaphores

  • Binary (value: 0 or 1) — acts like a mutex: only one holder at a time
  • Counting (value: N) — allows up to N concurrent holders

Linux uses both: mutex_lock/mutex_unlock for mutual exclusion, down/up in the VFS for I/O synchronization.

Your Task

Implement sem_down (returns 1 if acquired, 0 if blocked) and sem_up.

TCC compiler loading...
Loading...
Click "Run" to execute your code.