# Prevent task switching during specific code execution

**URL:** <https://forums.freertos.org/t/prevent-task-switching-during-specific-code-execution/13973>\
**Category:** Kernel\
**Created:** [November 29, 2021, 9:25pm UTC](https://forums.freertos.org/t/prevent-task-switching-during-specific-code-execution/13973 "2021-11-29T21:25:49Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Rik001](https://avatars.discourse-cdn.com/v4/letter/r/bbce88/32.png) [@Rik001](https://forums.freertos.org/u/Rik001)\
**Post date:** [November 29, 2021, 9:25pm UTC](https://forums.freertos.org/t/prevent-task-switching-during-specific-code-execution/13973/1 "2021-11-29T21:25:50Z")

</div>

Hi,  
I have a very small piece (literally just few lines) of code that I want to ensure is fully executed without being interrupted by task switching.  
What is the best/correct way to do it?  
Is vTaskSuspendAll() the way?  
Thank you  
Rick

---

<div class="post-metadata">

**Author:** ![hs2](https://avatars.discourse-cdn.com/v4/letter/h/a4c791/32.png) [@hs2](https://forums.freertos.org/u/hs2)\
**Post date:** [November 29, 2021, 9:42pm UTC](https://forums.freertos.org/t/prevent-task-switching-during-specific-code-execution/13973/2 "2021-11-29T21:42:52Z")

</div>

This is a pretty good thread when to use which tool for mutual exclusion:

> [@How to choose a critical section protecton approach? taskENTER\_CRITICAL or vTaskSuspendAll or mutex?](https://forums.freertos.org/t/how-to-choose-a-critical-section-protecton-approach-taskenter-critical-or-vtasksuspendall-or-mutex/9500):
>
> The first question is how to choose between taskENTER\_CRITICAL and vTaskSuspendAll? I have read the manual and found that taskENTER\_CRITICAL will disable interrupt while vTaskSuspendAll won’t disable interrupt but only suspend the scheduler. However, I still cannot understand the rational behind API [xQueueGenericSend](https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/10bbbcf0b9bcab1869b3bac3987d32116f351718/queue.c). In xQueueGenericSend, the code1 between line 761 and line 897 uses taskENTER\_CRITICAL to protect itself, while the code2 between line 902 and line 941 uses vTaskSuspendAll to prot…

In case you simply want to have the code executed as fast as possible and deterministically i.e. without any interruption you have to use a critical section.  
If you’re using interrupts outside FreeRTOS covered (priority) range you might want disable interrupts globally e.g. using \_\_disable/enable\_irq intrinsics for ARM MCUs.
