In avr-gcc you can something like this:
ATOMIC_CODE{
cout << "Here I can do stuff that is very time sensitive\n";
}
Unfortunately this is a #define which uses a special gcc atribute, which I would like to avoid.
So a workaround is this:
void enableInterrupts(){ std::cout << "Interupts Enabled\n"; }
void disableInterrupts() { std::cout << "Interupts Disabled\n"; }
class Scoped{
void (*cleanup)();
bool incremented;
public:
Scoped(void (*clean)(),void (*before)()) : cleanup(clean),incremented(false){
before();
}
~Scoped(){
cleanup();
}
void operator ++(){
incremented = true;
}
bool operator!(){
return !incremented;
}
};
#define ATOMIC for (Scoped x(&enableInterrupts,&disableInterrupts); !x; ++x)
//Later in main.cpp
ATOMIC{
/*do stuff*/
std::cout << "This is atomic code\n";
}
The only problem is that it relys on the destructor getting called immediately (which I am not sure is a reliable method).
So is it guaranteed that the destructor will get called immediately or can the compiler destruct the object whenever it feels like it?
Yes, it is guaranteed that the destructor will be called immediately.
https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
You're thinking about languages that do lazy mark and sweep garbage collection. (ok, maybe you're not)