如何使用宏来替换用于锁定函数的赋值操作

时间:2016-03-29 03:12:37

标签: c++ 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;

但是,无法编译。错误:

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;
}

1 个答案:

答案 0 :(得分:1)

从functionLock define的最后一行删除\。