AdvancedTopic 79 of 104Electronics & Embedded

Mutexes and semaphores

Synchronise tasks and protect shared resources.

In depth

A mutex gives exclusive access to a shared resource, a semaphore counts available resources or signals events. Misuse causes deadlock, priority inversion and race conditions. Use short critical sections; prefer message queues for data transfer.

Key points

  • Binary vs counting semaphores
  • Lock ordering
  • ISR-safe API variants
Example

Two tasks sharing a UART protect it with a mutex.

Why it matters

Shared resources must be protected from simultaneous access, or data becomes corrupted, so mutexes and semaphores are used in every multitasking system.

Where this is used

  • Protecting a shared sensor buffer from two tasks.
  • Limiting access to a communication bus to one task at a time.
  • Signalling a task that new data has arrived using a semaphore.

Frequently asked questions

What is Mutexes and semaphores?

Synchronise tasks and protect shared resources.

Why is it important to understand mutexes and semaphores?

Shared resources must be protected from simultaneous access, or data becomes corrupted, so mutexes and semaphores are used in every multitasking system.

What is the difference between a mutex and a semaphore?

A mutex guards a resource and is owned by one task. A semaphore is a counter for signalling or limiting access, and any task can post it.

What is a deadlock?

When tasks wait for each other's resources forever, which can be avoided with consistent lock order and timeouts.

How is Mutexes and semaphores used in practice?

Typical applications include protecting a shared sensor buffer from two tasks, limiting access to a communication bus to one task at a time and signalling a task that new data has arrived using a semaphore.

What should I learn before Mutexes and semaphores?

Study "Task scheduling" first (topic 78 of 104 in Electronics & Embedded). It covers the groundwork this topic builds on.

What are the key points of Mutexes and semaphores?

Binary vs counting semaphores. Lock ordering. ISR-safe API variants.

Can you give an example of Mutexes and semaphores?

Two tasks sharing a UART protect it with a mutex.

What comes after Mutexes and semaphores?

The next topic is "Priority inversion", which builds directly on this one.

How difficult is Mutexes and semaphores?

It is classed as Advanced in Electronics & Embedded (topic 79 of 104). It is an advanced topic. It assumes you are comfortable with the intermediate topics in Electronics & Embedded.

Learning path

Want to practise? Open the interactive course for quick checks, quizzes, simulations and progress tracking.

Related topics