Skip to main content
Rudolph Berger
Associate
Mar 6, 2019 4:05 PM UTC
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?

Cheers and thanks a lot.

This topic has been closed for replies.

1 reply

alister
Senior III
Mar 6, 2019 11:15 PM UTC

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).