Specifications
CAVR-4
Part 1. Using the compiler
Functions
31
The following is an example of a program fragment that uses the semaphore:
void my_program(void)
{
if (get_lock())
{
/* ... Do something ... */
/* When done, release the lock. */
release_lock();
}
}
The drawback using this method is that interrupts are disabled for the entire monitor
function.
Example of implementing a semaphore in C++
In C++, it is common to implement small methods with the intention that they should be
inlined. However, the AVR IAR C/C++ Compiler does not support inlining of functions
and methods that are declared using the
__monitor keyword.
In the following example in C++, an auto object is used for controlling the monitor
block, which uses intrinsic functions instead of the
__monitor keyword.
#include <inavr.h>
volatile long tick_count = 0;
/* Class for controlling critical blocks */
class Mutex
{
public:
Mutex ()
{
_state = __save_interrupt();
__disable_interrupt();
}
~Mutex ()
{
__restore_interrupt(_state);
}
private:
unsigned char _state;
};