cancel
Showing results for 
Search instead for 
Did you mean: 

STREX/LDREX question

root
Associate II
Posted on December 04, 2013 at 19:47

Hello,

I'd like to implement synchonization with LDREX / STREX. What I don't understand is when I have multiple values to access with synchronization ...

void task1(void) 
{ 
ldrex var1; 
while(!strex(var1)); 
do_whatever(); 
} 
void task1(void) 
{ 
ldrex var2; 
while(!strex(var2)); 
do_whatever_else(); 
}

(syntax is wrong but you get it). Now what happens if task1 executes its ldrex, is preempted, context switch to task2, then task2 executes ldrex, then strex (what would be the result there ?), then context switch to task1 and task1 executes its ldrex ? If it is unpredictable, then it means application should always use the same location for ldrex/strex, or did I miss something? Thomas.
1 REPLY 1
root
Associate II
Posted on December 04, 2013 at 22:51

Ok I think I got it ...

This is where the 3rd instruction comes into play : CLREX.

If the OS preempts execution of task1 and switch the context to task2, it has to execute a CLREX instruction. That way before context switch the monitor is in the exclusive state, CLREX re-opens it, so that task2 can do its atomic operation (resulting in monitor in open state), and when context is switched back to task1, the CLREX instruction will make the STREX instruction from task1 to fail (but task one just need to iterate to get the lock).

And you have to do this each time you are preempt an execution susceptible to use LDREX/STREX instructions (it means if you want to use LDREX/STREX instructions in both thread level and interrupt level, you need to call CLREX in the interrupt level).

A good practice could be to use always call CLREX before the LDREX/STREX loop.

And still use CLREX in case of context switching.

Am I right?

Thomas.