Search code examples
multithreadingkeilrtoscmsis

What is the best way to block all threads except one?


I am working on a project where I need to block all threads when a certain thread starts execution. I have considered using thread flags, but I believe this would involve adding checks to all the threads. I have also considered using a mutex to block all threads except the critical thread which I need to execute/have sole control of the processor. The reason why I haven't yet used a mutex is because I have read that it only relates to resources and that some threads would still continue to execute if they are not linked to the mutex, however I may have misunderstood this.

Could you please tell me if my approach to the mutex idea is correct or if I should use another method?

Edit: I am using Keil RTX 5/CMSIS RTOS 2 on the STM32H753 chip

Thanks


Solution

  • The CMSIS RTOS has a pair of functions osKernelLock() and osKernelUnlock() - dynamically modifying thread priorities or using mutexes is unnecessary and probably ill-advised.

    Any other RTOS will have similar critical section API.

    Note that this only prevents task context switching; it does not prevent interrupts from running. This is normally desirable, but if you want to prevent that, you can simply disable all interrupts using _disable_irq()/_enable_irq(). That will prevent task switched and interrupts.

    Disabling interrupts is brute-force and has a greater impact on the real-time behaviour of your system that even a scheduler lock. Generally it should be done only for very short periods (as should scheduler locking).