cancel
Showing results for 
Search instead for 
Did you mean: 

Atomic Operation

primagen23
Associate II
Posted on September 18, 2012 at 21:20

Hi,

as i know stm32 operations alway read-modify-write. Not atomic.

If i read below it looks like C is already atomic for some operations. Or is it not guarantee on stm32 platform?

http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=469
3 REPLIES 3
Danish1
Lead II
Posted on September 18, 2012 at 22:04

That web page just says that for that particular processor, the author thinks that those operations happen to be atomic. I expect that an interrupt would not occur half-way through a single instruction, but I would be less certain that it is atomic on a system with multiple processors or multiple cores (as most Win32 systems are).

In general you cannot rely on things being atomic if you have multiple threads and interrupts all (apparrently) executing at the same time.

Where there is one main thread and interrupts I tend to rely on flags, or treat each volatile item as read-only in my main thread and updating it only in the interrupt.

Where there are multiple threads, you might be rolling your own thread-management code or you could use an existing library. That library will have to be thread-safe, and so it will probably have atomic semaphore operations. I use the Crossworks Tasking Library (CTL) but there are many real-time operating-systems that provide all the necessary routines.

Failing that, the simplest approach is to disable interrupts immediately before, and re-enable interrupts immediately after, the sequence of instructions you want to be atomic.

Hope this helps,

Danish

emalund
Associate III
Posted on September 19, 2012 at 16:57

someone (me?) is confoosed

for any processor everything that is less than or equal to a processors memory width is atomic.

BTW C, by itself, has no atomicity

Erik
Danish1
Lead II
Posted on September 21, 2012 at 19:38

Hi Erik,

A single read or single write of a byte, half-word, or word *is atomic.

But the issue is where you are doing e.g. an increment ++i;

The compiler turns that into a read into a register, then the arithmetic, then a write back into memory.

And the issue of atomicity comes in if either an interrupt or e.g. a DMA access updates i between the read and the write. What then happens is that the write-back overwrites the new value with something based on the old value. It looks as though the interrupt never updated i.

*Unless it is a non-aligned read or write, which the stm32 core is forced to turn into two accesses.

Note: Disabling interrupts, as I suggested earlier, does not solve the problem where the competing write comes from the DMA controller.

You are right C has no atomicity but then it has no intrinsic support for multiple threads - other than the volatile keyword which tells the optimiser to keep all reads and writes to that variable.

 - Danish