Skip to main content
Rudolph Berger
Associate
March 6, 2019
Question

Hello, I'm using FreeRTOS and I'am wondering if the HAL Driver functions are thread safe. So if I call for example the HAL_I2C_Master_Transmit function from multiple threads, do they interfere with each other, or are they thread safe?

  • March 6, 2019
  • 1 reply
  • 1270 views

Cheers and thanks a lot.

This topic has been closed for replies.

1 reply

alister
Senior III
March 6, 2019

If you read stm32f7xx_hal_i2c.c you'll observe __HAL_LOCK() isn't thread safe because it doesn't atomically test and set (__HANDLE__)->Lock. I.e. task A tests and finds it's unlocked, and task B preempts it and also finds it's unlocked and locks it, task A resumes and locks it too.

The API isn't thread-safe more than one way.

  1. Tasks may call the same function and fail in some fashion.
  2. Tasks may call different functions and fail in some fashion.

The general options are:

  1. Wrap the entire API with a mutex.
  2. Design your software so only one task accesses the I2C peripheral, e.g. using a queue or ring-buffer/signal, and possibly state-machine.

Option 2 is the better option IMHO because its software is more organised and more easily comprehended (i.e. less bugs).