|
|
The **Active Object** design pattern decouples method execution from method invocation.
|
|
|
An active object is an object that "runs" in a *separate thread*.
|
|
|
|
|
|
It can be useful for in a situation in which an object has to periodically pop elements from a queue, which are in turn produced by a second thread or for example for a receiver object that has to continuously check for incoming messages.
|
|
|
|
|
|
### Interface
|
|
|
|
|
|
In `src/shared/` you can find the corresponding template.
|
|
|
The most relevant functions are:
|
|
|
- **Constructor**: creates a Miosix Thread.
|
|
|
- **threadLauncher**: private static function that is executed from the Thread, calls the run() method.
|
|
|
- **run**: protected method, should be overridden with the code that you want to run on the Thread.
|
|
|
|
|
|
In order to start the active object you can call `start()` while you can call `stop()` in order to stop it.
|
|
|
|
|
|
### Example
|
|
|
|
|
|
```cpp
|
|
|
/*
|
|
|
* The Receiver class is an ActiveObject that reads incoming packets from the RF
|
|
|
* module and forwards an event to the EventBroker accordingly to the received
|
|
|
* message.
|
|
|
*/
|
|
|
class Receiver : ActiveObject {
|
|
|
|
|
|
public:
|
|
|
/* Constructor: sets the RF driver to use */
|
|
|
Receiver(Gamma868* gamma) {
|
|
|
this->gamma = gamma;
|
|
|
}
|
|
|
|
|
|
/* Deconstructor */
|
|
|
~Receiver() {}
|
|
|
|
|
|
protected:
|
|
|
/*
|
|
|
* Function executed in a separate thread: waits for a packet and forwards
|
|
|
* the corresponding event.
|
|
|
*/
|
|
|
void run() {
|
|
|
// Infinite loop
|
|
|
while(1) {
|
|
|
// Do stuff
|
|
|
}
|
|
|
}
|
|
|
|
|
|
private:
|
|
|
Gamma868* gamma;
|
|
|
|
|
|
};
|
|
|
``` |
|
|
\ No newline at end of file |