This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Racing adventure in OS

Hi,Master:

 

Question 1:

As shown in the below, why does the api read this variable with critical protection?

INT32U  OSTimeGet (void)
{
    INT32U     ticks;
#if OS_CRITICAL_METHOD == 3u                     /* Allocate storage for CPU status register           */
    OS_CPU_SR  cpu_sr = 0u;
#endif



    OS_ENTER_CRITICAL();
    ticks = OSTime;
    OS_EXIT_CRITICAL();
    return (ticks);
}

Question 2:

Suppose two tasks have write operations to shared variables. For example:

int var;
void task1(void)
{
    OS_ENTER_CRITICAL();
    var = 1;
    OS_EXIT_CRITICAL();
}

void task2(void)
{
    OS_ENTER_CRITICAL();
    var = 2;
    OS_EXIT_CRITICAL();
}

In the OS source code, you can see that a critical section must be added to the shared variable write operation. There is no read-modify-write, and it should not cause a race condition. Why do you need to add a critical section?

 

Question 3:

If the compiler has done level optimization, there may be a write cache for variable writes. In this case, should the DSB data synchronization barrier be increased after the variable is written in the critical section? I don’t know when to use DSB, ISB, etc. instructions

 

Thank you very much.

Parents
  • Hi,

    Regarding Q1, I do not know where this code comes from so I cannot comment on why this is done like it is.

    Regarding Q2, you are right that as this is a pure write (no read-modify-write) there is no need for a critical section here, even if the same variable is written to by two tasks. I cannot see that it serves any purpose. (The variable should be volatile though (assuming it is also read somewhere), so that the compiler does not optimize away reading of the variable, thinking it know what it is set to.)

    Regarding Q3, there are some situations where you want to use the DSB/ISB instruction but I do not see any particular reason you would need that here (there is no context here, though).

Reply
  • Hi,

    Regarding Q1, I do not know where this code comes from so I cannot comment on why this is done like it is.

    Regarding Q2, you are right that as this is a pure write (no read-modify-write) there is no need for a critical section here, even if the same variable is written to by two tasks. I cannot see that it serves any purpose. (The variable should be volatile though (assuming it is also read somewhere), so that the compiler does not optimize away reading of the variable, thinking it know what it is set to.)

    Regarding Q3, there are some situations where you want to use the DSB/ISB instruction but I do not see any particular reason you would need that here (there is no context here, though).

Children
No Data
Related