</>EmbeddedInterview

What is the difference between a mutex and a binary semaphore?

MediumRTOS & Real-Time Systems

Short answer: A mutex is for mutual exclusion: it has an owner, only the task that took it may give it back, it supports priority inheritance, and it can be recursive. A binary semaphore is for signalling: it has no owner, any task or ISR can give it, and it has no priority inheritance. Use a mutex to protect a shared resource; use a semaphore (or a task notification) to signal that an event happened.

Mutex Binary semaphore
Purpose protect a resource (critical section) signal an event / synchronise
Ownership yes: only the holder releases it no: anyone can give
Priority inheritance yes (FreeRTOS, Zephyr) no
Usable from an ISR no (an ISR cannot own/block) give from ISR: yes (xSemaphoreGiveFromISR)
Recursive variant yes (xSemaphoreCreateRecursiveMutex) no
Initial state available usually empty (0)

Typical patterns

/* mutex: protect a shared I2C bus */
if (xSemaphoreTake(i2c_mutex, pdMS_TO_TICKS(10)) == pdTRUE) {
    i2c_read(...);
    xSemaphoreGive(i2c_mutex);
}

/* binary semaphore: ISR signals a task */
void EXTI0_IRQHandler(void)
{
    BaseType_t woken = pdFALSE;
    clear_exti_flag();
    xSemaphoreGiveFromISR(button_sem, &woken);
    portYIELD_FROM_ISR(woken);
}
void button_task(void *p) { for (;;) { xSemaphoreTake(button_sem, portMAX_DELAY); handle_press(); } }

Why it matters: using a binary semaphore as a lock loses priority inheritance (priority inversion risk), and nothing stops another task from "unlocking" it by mistake. Using a mutex for signalling fails because the giver does not own it.

Modern FreeRTOS advice: for "ISR wakes one task", use a direct-to-task notification (vTaskNotifyGiveFromISR / ulTaskNotifyTake): faster and uses less RAM than a semaphore.