cancel
Showing results for 
Search instead for 
Did you mean: 

On a 32-bit processor, can an ISR and the main loop share an int32?

Chris Rice
Associate III
Posted on June 08, 2018 at 21:20

This may be a galactically stupid question, but I'm an 8-bit programmer making the leap to 32-bit programming.

On 8-bit CPUs, we could 'share' (read and set) a 1 byte (char, uint8_t) variable between ISRs and the main loop.  Setting or reading it was atomic, so the ISR could set a flag and the main loop could read it, without corruption by interrupting between assembly instructions.

Is the same true, by chance, for 32-bit processors and 32 bit variables (uint32_t, int32_t)?  Can I read to and write from a single 32-bit variable from ISRs and main loop with impunity?

(I'm guessing I'm not so lucky.  In fact now I'm hoping nobody shoots down my 8-bit assertion as a premise...)

Thanks!

#isr #atomic
6 REPLIES 6
David SIORPAES
ST Employee
Posted on June 08, 2018 at 22:23

Sure you can.

Cortex-M instruction set provides atomic load/store exclusive instructions LDRX, STRX as well as byte and half-word variants.

See 

http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0553a/BABFFBJB.html

 and 

http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0553a/BABFFBJB.html

T J
Lead
Posted on June 09, 2018 at 01:27

I declare a table and flags in main.h

then every module can access it directly.

I use the DMA ADC to fill that table and set the flags, then the foreground loop can work at it own pace, checking buffer levels and completion flags.

henry.dick
Senior II
Posted on June 09, 2018 at 11:53

'

Is the same true, by chance, for 32-bit processors and 32 bit variables (uint32_t, int32_t)?'

yes, and also true for non-32-bit types -> you just need to be careful with atomicity.

Posted on June 11, 2018 at 02:54

Hello, thank you.  Do you think that I can trust that a reputable C compiler (I'm using Keil, so it's good) will use these atomic instructions for general read/writes to a uint32_t?   Or should I inspect the assembly code for each possible conflict and confirm that it's using these commands?  Or should I consult my compiler documentation?

Thanks... not asking you to research for me, just wondering what your gut feeling is.

Posted on June 11, 2018 at 02:55

Thank you dhenry.  Similar question as mine above for David: do you think that I can trust that a good C compiler will be 'careful with atomicity', or should I inspecting assembly at every get and set?  Thanks.

Posted on June 11, 2018 at 10:20

The compiler will generate ordinary LDR/STR instructions for reading/writing uint32_t or any other type.

You must explicitly use LDREX/STREX instructions to access the shared variable. Keil offers intrinsics for this but they are deprecated 

http://www.keil.com/support/man/docs/armcc/armcc_chr1359124997286.htm