cancel
Showing results for 
Search instead for 
Did you mean: 

Atomic read of an variable

sima
Associate II
Posted on April 01, 2009 at 20:23

Atomic read of an variable

7 REPLIES 7
ccowdery9
Associate III
Posted on May 17, 2011 at 13:08

a vu8 is a single memory location or part of a register, and you've declared it volatile. So reading it must be atomic (it's not as if it's part of a structure or multi-register timer value).

If you're using it multiple times in an expression, then it might have changed value mid-expression, so in that case you need a local copy of it.

Chris.

sima
Associate II
Posted on May 17, 2011 at 13:08

If I have a variable:

vu8 important_value;

And I write to this variable in my interrupt function.

Then in my main loop I read this variable continiously.

Is the read operation in the main loop going to be atomic or can there be some side effects?

And what if i use vu16 or vu32?

I have read that one should turn of the interrupt while reading the variable so the interrupt doesn't change it while the read is in progress. But this vu8 could be read in one assembler instruction (vu8, vu16 or vu32) in the STM32 (or does it)?

[ This message was edited by: sima1 on 30-03-2009 14:05 ]

trevor1
Associate II
Posted on May 17, 2011 at 13:08

The same applies to vu16 and vu32 as these also are a single memory location on STM32.

sima
Associate II
Posted on May 17, 2011 at 13:08

I found an interesting thing in:

http://www.st.com/mcu/files/mcu/1221142709.pdf

at ''2.3.6 Unaligned Memory Accesses''

But is this only for structures?

Are normal variables always aligned at 32bit boundaries? Or must I insert some alignment rules in my code?

picguy
Associate II
Posted on May 17, 2011 at 13:08

It helps (timing wise) to have 16 and 32-bit memory appropriately aligned. For load or store single register (ldr/str) unaligned operations it works. However, attempts to load or store multiple (ldm/stm) unaligned fail.

One presumes your compiler knows this and will not generate an unaligned load multiple. Normal 32-bit variables *should* be word aligned but Cortex does not demand this as (I believe) is the case with ARM7.

Nothing in this discussion is unique to C structures. It’s just that structs are a good way to produce unaligned variables.

st3
Associate II
Posted on May 17, 2011 at 13:08

I thought one of the selling points of the Cortex-M3 core was that it was supposed to handle unaligned accesses without penalty?

Was I mistaken?

picguy
Associate II
Posted on May 17, 2011 at 13:08

Sometimes no penalty. Load or store a halfword in the middle of a 32-bit word = no penalty. The same operations crossing word boundaries = one cycle delay. Do the word crossing load or store 72,000,000 times and your penalty is one second. I would not be inclined to worry.