[Linux Internals] Mutexes and Semaphores; Why we need them?

Problem Statement:

  1. Data is shared between several tasks and, in order to keep the data in a consistent state, we need to protect it from concurrent access. How? One of the many other ways is, Mutex.
  2. Task synchronization: how does the consumer know that [new] data is available? semaphores


The concept of ownership is very important here: the task that acquired the mutex must release it as well! Bad things will happen when:

  • another task releases the mutex, or
  • the task never releases the mutex, etc.

Ownership has other consequences as well e.g. it is prone to deadlocks and priority inversion etc.

The mutex implements two operations:

  • acquire: enter the critical section, or sleep if another task has already acquired the mutex, and
  • release: leave the critical section. Other tasks now have the possibility to acquire the mutex.

Semaphore is a non-negative variable and shared between threads to achieve proper process synchronization in the multiprocessing environment. Its mainly used to solve the critical resource access problem.
Apart from initialization, semaphore is accessed ONLY through 2 standard operations : wait() or signal().

signal: which is used by a producer to notify the consumer

wait: which is used by the consumer to wait for a notification

Definition of wait():P(Semaphore S) {
while (S<=0)
; // no operation; Not allowed to use the resource
S--; // means S > 0; allowed to use the resource
Definition of signal():V(Semaphore V) {
// singal() will notify the process that I am done with this resource; anyone can use it !
S++; // releasing the semaphore/resource

When a process is modifying the semaphore , no other process modify the same semaphore.

Two types of semaphores:

Binary semaphore: Value can be 0 or 1; also called as mutex locks; Used for mutual exclusion

Counting semaphore: Value can be ≥ 0; Used to control access to a resource that can be used by multiple processes. Mainly used for counting events or resource management scenarios.

Source URL: https://www.freertos.org/Real-time-embedded-RTOS-Counting-Semaphores.html



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


Passionate about learning ; Will write about #systemdesign #DSA #algorithms #linuxinternals #technology; Painting/Poem writing are my hobbies; Voracious Reader