Replacement for AVR libc ATOMIC_BLOCK macros, now for DUE and other platforms.

WizenedEE:

pico:
Also, since the original ATOMIC_BLOCK macros are actually based on a "for" loop under the hood to specify the code block, it would be theoretically possible to inadvertantly place a "break" or "continue" statement in such a block, and the compiler would not pick it up as out of place. Not a biggie in practice, but a bug yours doesn't suffer from.

Actually no.

Actually, yes.

Try compiling the following code. The compiler happily accepts the break and continue statements in the setup() function, but rejects them in the loop() function.

#include <util/atomic.h>

void setup()
{
  ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
  {
    int a =0;
    if (a++ > 0) continue;
    else break;
  }
}

void loop()
{
  int a =0;
  if (a++ > 0) continue;
  else break;
}

The compiler messages are:

sketch_oct04a.cpp: In function 'void loop()':
sketch_oct04a:16: error: continue statement not within a loop
sketch_oct04a:17: error: break statement not within loop or switch

OTOH, comment out the offending code in the loop() function, and the compiler accepts the break and continue statements in the setup() function happily.

Binary sketch size: 456 bytes (of a 32256 byte maximum)

Since it's a "for" loop, I can't see how the compiler could NOT be expected to accept both break and continue statements as legal C statements in that context (because they are).

A bug, but one of perhaps of theoretical interest only. Still, it's a bug Pyro's approach doesn't suffer from, which was my point.

On a practical note, the other advantage of the ATOMIC_BLOCK macros over anything else that is likely to be a contender is that the macros have been very carefully tested for all the subtle problems that can occur with instruction reordering optimisations, etc. The story behind the development by Dean Camera (abcminiuser) was documented in an interesting thread on AVRFreaks.

http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&t=45041&postdays=0&postorder=asc&highlight=atomic

It would take a fair degree of analysis and testing before any replacement would reach the same level of acceptance, I think.