Home > front end >  FreeRTOS task interrupting other tasks
FreeRTOS task interrupting other tasks

Time:09-29

I am learning about mutex and semaphore. And got a quick question to clarify:

void task1(void* parameter){
    while(1){
        global_var  ;
    }
}


void task2(void* parameter){
    while(1){
        global_var  ;
    }
}

    xTaskCreate(task1,"task1",10000,NULL,1,NULL); // receiving modem input
    xTaskCreate(task2,"task2",10000,NULL,1,NULL); // receiving modem input

If I have 2 tasks that are accessing one global variable. Is there a possibility if one task will interrupt another task if both are the same priority? Or the issues only start happening when one command is different priority or the task is being interrupted via the timer or other interrupts?

CodePudding user response:

The tasks are getting scheduled by the operating system (f.e.: freertos). It depends on which scheduling technique is used. If it uses Round-Robin, the tasks are scheduled fairly, which means task2 will be scheduled after (defined timeslice) task1. Which means no starvation.

But as you mentioned if there is a interrupt, the ISR will be executed instead of task1 or task2.

A example can be found on: freertos page

There are two sheduling policies: FreeRTOS kernel supports two types of scheduling policy: Time Slicing Scheduling Policy: This is also known as a round-robin algorithm. In this algorithm, all equal priority tasks get CPU in equal portions of CPU time. Fixed Priority Preemptive Scheduling: This scheduling algorithm selects tasks according to their priority. In other words, a high priority task always gets the CPU before a low priority task. A low priority task gets to execute only when there is no high priority task in the ready state. (from https://microcontrollerslab.com/freertos-scheduler-learn-to-configure-scheduling-algorithm/)

You can select scheduling algorithms by setting corresponding configuration bits (flags/defines) in theFreeRTOSConfig.h file.

CodePudding user response:

Yes, both tasks will be scheduled alternately and thus can "interrupt" each other. By default, the tasks will be switched every millisecond.

Since both tasks share a resource (the global variable) and the increment operation is (in general) not atomic, you should indeed use a mutex to prevent possible errors.

NB: A mutex is not the same as a semaphore. Since you want MUTual EXclusion in this case, a mutex is the right solution.

(Note: this is only true if FreeRTOS is configured to use preemptive scheduling with time slicing, i.e. configUSE_PREEMPTION == 1 amd configUSE_TIME_SLICING == 1, which is the default.)

  • Related