Page 1 of 1

TWAI_TRANSMIT thread safety

Posted: Fri Dec 15, 2023 4:42 pm
by tomRoberts
Is it safe to use twai_transmit() from multiple tasks?

If not, are critical sections appropriate like so:
  1. //Disables interrupts and context-switching during twai_transmit
  2. void threadSafeTwaiTransmit(twai_message_t message){
  3.     taskENTER_CRITICAL(&my_spinlock);
  4.     twai_transmit(&message, pdMS_TO_TICKS(0));//(message, ticks to wait if tx queue full)
  5.     taskEXIT_CRITICAL(&my_spinlock);
  6. }
Or is it better to pass messages to a single task for transmission?

Re: TWAI_TRANSMIT thread safety

Posted: Sat Dec 16, 2023 6:09 pm
by MicroController
tomRoberts wrote:
Fri Dec 15, 2023 4:42 pm
Is it safe to use twai_transmit() from multiple tasks?
Yes, like most IDF driver functions (which don't state otherwise in the documentation) it is safe to be called concurrently.
If not, are critical sections appropriate like so:
  1. //Disables interrupts and context-switching during twai_transmit
  2. void threadSafeTwaiTransmit(twai_message_t message){
  3.     taskENTER_CRITICAL(&my_spinlock);
  4.     twai_transmit(&message, pdMS_TO_TICKS(0));//(message, ticks to wait if tx queue full)
  5.     taskEXIT_CRITICAL(&my_spinlock);
  6. }
Or is it better to pass messages to a single task for transmission?
In this specific case, it would happen to be ok to use a critical section, but not at all necessary. A FreeRTOS mutex is a more multi-tasking and interrupt friendly means for achieving mutual exclusion, which would be sufficient here.
Passing messages to a dedicated task via a queue is also a valid approach, with the potential added benefit that these messages could also be sent from an ISR if needed.