-
Notifications
You must be signed in to change notification settings - Fork 5
1. Overview
Let say we have next code:
double temperature;
char has_new_measurement;
void temp_measurement_interrupt();
{
temperature = ...
has_new_measurement = 1;
}
void handle_temp_change()
{
... // do something with temperature
}
void main()
{
while(1)
{
if (has_new_measurements)
{
handle_temp_change();
has_new_measurements = 0;
}
}
}Disadvantages of this approach are obvious:
- Thread unsafity: what will be when we try to read temperature in
handle_temp_changewhiletemp_measurement_interruptis writing a new value? - Leak of values, when several values have come, but not yet handled. Previous values are lost.
- Boilerplate code.
- Global variables.
So with a messages channel it can be changed to next:
#include "events-engine.h"
void handle_temp_change(double *temperature);
DataStream(TemperatureMeasured, double, 3)
{
bindHandler(handle_temp_change);
}
void handle_temp_change(double *temperature)
{
... // do something with temperature
}
void temp_measurement_interrupt()
{
publishData(TemperatureMeasured, double* temperature) *temperature = ...
}
void main()
{
while(1) handleEvent(TemperatureMeasured);
}Lets look at example above. Firstly you should declare a channel with next code:
DataStream(TemperatureMeasured, double, 3)
{
bindHandler(handle_temp_change);
}It means that we have the channel named TemperatureMeasured, with the message type double and the size 3. So the channel can store 3 messages. When more than 3 messages is come without handling, the new one will be lost.
And when some message is come, handle_temp_change will be executed.
void temp_measurement_interrupt()
{
publishData(TemperatureMeasured, double* temperature) *temperature = ...
}publishData enables us to put some data into the channel. Some place in the channel will be allocated and become available via the temperature pointer. Also you can put your code between brackets:
void temp_measurement_interrupt()
{
publishData(TemperatureMeasured, double* temperature)
{
*temperature = ...
}
}If the channel doesn't have enough space for new message, code inside of the block won't executed.
At the end we run a handling mechanism with handleEvent(TemperatureMeasured). It checks if some messages exists inside of the channel and call the handle_temp_change handler when a message occurs. It processes just one message, not all messages in the channel.