How to use Mutex in ESP-IDF

If you are running multiple threads, chances are that they may be accessing some resources/peripherals that are critical, and should be accessed only by one thread at a time. Examples of peripherals are SPIFFS storage or SD Card. So how do you make one thread wait while another one is executing? The answer is Mutex (short for Mutual Exclusion). You can think of it as a flag that can be set to 1 by a thread accessing a resource and reset to 0 when the thread releases that resource. All other threads have to wait till the flag is reset, before accessing that resource. You can read more about Mutex here.

How do you create a Mutex in esp-idf? Here are the steps.

Make the inclusion

#include <pthread.h>

Declare the Mutex

static pthread_mutex_t spiffsMutex;

Initialize the Mutex

if(pthread_mutex_init (&spiffsMutex, NULL) != 0){
  printf("Failed to initialize the spiffs mutex");
}

The initialization should be done only once at the start of the code.

You can find the documentation for the init function here. The first argument is the pointer to the mutex, and the second argument is a pointer to a pthread_mutexattr_t struct. Since we have specified NULL, default mutex attributes are used. Usually NULL is good enough for most applications. But if you are really interested, you can read more about what attributes you can supply here.

Lock mutex before accessing a critical resource, and then unlock it

if(pthread_mutex_lock(&spiffsMutex) == 0){
  //Access spiffs and perform operations

  //Unlock once operations are done
  pthread_mutex_unlock(&spiffsMutex);
}

If the mutex is already locked when the pthread_mutex_lock is called, the thread calling this function shall remain blocked till the mutex is unlocked. If you wish to avoid this blocking of the thread, you can use pthread_mutex_trylock() instead. This function returns immediately if the mutex is already locked.

(Optional) Destroy the mutex once it is no longer needed

if(pthread_mutex_destroy (&spiffsMutex) == 0){
  printf("Mutex destruction failed");
}

That’s it. Hope you liked this article.


For more tutorials on ESP32, check out https://iotespresso.com/category/esp32/. Also, you may find this course on ESP32 on Udemy to be quite helpful. Do check it out

Leave a comment

Your email address will not be published. Required fields are marked *