在avr-gcc中你可以这样:
ATOMIC_CODE{ cout << "Here I can do stuff that is very time sensitive\n"; }不幸的是,这是一个使用特殊gcc 属性的#define,我想避免使用它。
所以解决方法是:
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"; }唯一的问题是它依赖于立即调用析构函数(我不确定它是一种可靠的方法)。
那么是否可以保证析构函数会立即被调用,或者编译器可以在它感觉到的时候破坏对象?
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?
最满意答案
是的,保证会立即调用析构函数。
https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
你正在考虑做懒惰标记和扫描垃圾收集的语言。 (好吧,也许你不是)
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)
更多推荐
发布评论