在一個函數的開始,我把這個宏來防止再次進入功能:如何使用宏來替換賦值操作使用鎖定功能
//For locking ISRs to prevent re-entrant execution when nested interrupts are enabled
//-ex: to prevent re-entrant execution of this ISR even though ***nested interrupts are enabled!***
//-"return" is to exit the function if the ISR is locked
#define functionLock() \
static bool ISR_locked = false; \
if (ISR_locked==true) \
return; \
ISR_locked = true; \
這工作。
當時我想用這個宏函數的結束重新啓用下一個入口函數進去:
#define functionUnlock() ISR_locked = false;
但是,這無法編譯。錯誤:
error: '#' is not followed by a macro parameter
error: 'functionLock' was not declared in this scope
error: 'ISR_locked' was not declared in this scope
我的第二個宏有什麼問題?
如果我只是刪除第二個宏並使用「ISR_locked = false;」直接在函數的末尾,它一切正常,但我想有一個匹配的宏來結束函數,而不是使用該行。
我們的目標是在函數中使用這些宏,就像這樣:
void myISR()
{
functionLock(); //locks the function to prevent re-entrant execution
//do stuff
functionUnlock();
}
全小例子
#include <iostream>
using namespace std;
//macros:
//For locking ISRs to prevent re-entrant execution when nested interrupts are enabled
//-ex: to prevent re-entrant execution of this ISR even though ***nested interrupts are enabled!***
//-"return" is to exit the function if the ISR is locked
#define functionLock() \
static bool ISR_locked = false; \
if (ISR_locked==true) \
return; \
ISR_locked = true; \
#define functionUnlock() ISR_locked = false;
void myISR()
{
functionLock();
cout << "hello";
functionUnlock();
// ISR_locked = false;
}
int main()
{
myISR();
return 0;
}
你最好創建一個在構造函數中使用鎖並在析構函數中釋放的對象 - 那麼你不需要記得調用'functionUnlock()'。 –
@TonyD,你能指點我一個很好的例子嗎?鎖定功能的整個概念對我來說是一個新的領域。 PS。這是在ATmega328微控制器(Arduino)上運行的。 –
Try'struct ScopedLock {ScopedLock(bool&b):b_(b){b = true; }〜ScopedLock(){b_ = false;} },然後在你的'functionLock'宏中,用'ScopedLock isrLocker(&ISR_locked);'替換'ISR_locked = true;'。 –