protected data inside critical section

kolodko1 wrote on Sunday, October 26, 2008:

Hi

I have some doubts, please forgive trivial question.

from documentation about taskENTER_CRITICAL()
"Macro to mark the start of a critical code region. Preemptive context switches cannot occur when in a critical region."

We disable interrupts but other type of context switch can still happened(?)

lets consider that code, aim is protect variable "protectedVar":

============================================================
taskENTER_CRITICAL();

    protectedVar = something;
    (…)
        if( xQueueSendToBack( xQueue1,&ulVar,10 ) != pdPASS )
        {
      
        }
   
    (…)

    something2 = protectedVar+2;  // in this line var protectedVar could be corrupted because xQueueSendToBack() could cause context switch
       

taskEXIT_CRITICAL();

send message to other task with higher priority could cause context switch anyway, I have tested it on port PIC24.

My questions is:
1. Is it desirable feature of port what I use? in other words is my example code wrong from definition?

2. If answer on 1 is Yes, so is only cause why freeRTOS maintain separate uxCriticalNesting value for every task or maybe there are any other reasons?

Kind Regards
/Grzegorz K.

rtel wrote on Sunday, October 26, 2008:

> I have some doubts, please forgive trivial question.

Its not actually a trivial question.

> from documentation about taskENTER_CRITICAL() "Macro to mark
> the start of a critical code region. Preemptive context
> switches cannot occur when in a critical region."

The key here is ‘Preemptive’.  The critical region protects against preemptive context switches - what happens for other types of context switch actually depends on the port but for nearly all ports users can force a context switch within a critical section if they want.  It would not be normal to do so, but you have the flexibility if you want it.  One case where you may want this ability is to ensure that when a task starts executing again (gets switched back in) that it immediately has exclusive access to some resource.

Regards.

kolodko1 wrote on Sunday, October 26, 2008:

Thank You Richard.
That’s clear. May be useful if this hint will be in documentation, what you think?

So in theory, if I do not need that feature I can remove maintaining  uxCriticalNesting for every task and keep global variable? or there could be some side effects depend on port?

Best Regards
/Grzegorz K.

rtel wrote on Sunday, October 26, 2008:

> So in theory, if I do not need that feature I can remove
> maintaining uxCriticalNesting for every task and keep global
> variable? or there could be some side effects depend on port?

No - the kernel code itself uses the feature, although I am moving away from this reliance in the newer ports.  The critical nesting count has to remain as part of the task context.

Regards.