TWAI_TRANSMIT thread safety

tomRoberts
Posts: 1
Joined: Fri Sep 29, 2023 11:46 am

TWAI_TRANSMIT thread safety

Postby tomRoberts » Fri Dec 15, 2023 4:42 pm

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?

MicroController
Posts: 1708
Joined: Mon Oct 17, 2022 7:38 pm
Location: Europe, Germany

Re: TWAI_TRANSMIT thread safety

Postby MicroController » Sat Dec 16, 2023 6:09 pm

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.

Who is online

Users browsing this forum: Romaszewski and 76 guests