Macros
picotm-lib-state.h File Reference

Contains state helper macros. More...

#include <stddef.h>
#include "compiler.h"

Macros

#define PICOTM_STATE(_name, _type)
 
#define PICOTM_STATE_ACQUIRE(_name, _self, _initialize, _error)
 
#define PICOTM_STATE_INITIALIZER
 
#define PICOTM_STATE_RELEASE(_name, _self)
 
#define PICOTM_STATE_STATIC_DECL(_name, _type)
 
#define PICOTM_STATE_STATIC_IMPL(_name, _type, _init, _uninit)
 
#define PICOTM_STATE_TYPE(_name)
 

Detailed Description

Picotm provides helpers for managing state. State can be acquired and released as needed. When acquiring state, an initializer function sets up the state fields; when releasing the state, a clean-up function release the state fields. The example below declares state of type struct state

struct state {
int data1;
int data2;
};
void
init_state_fields(struct state* state, struct picotm_error* error)
{
state->data1 = 0;
state->data2 = 0;
}
void
uninit_state_fields(struct state* state)
{
// nothing to do
}
PICOTM_STATE(state, struct state);
PICOTM_STATE_STATIC_IMPL(state, struct state,
init_state_fields,
uninit_state_fields)

The macro PICOTM_STATE() defines state. Callers pass the state's name and data structure. The macro PICOTM_STATE_STATIC_IMPL() defines the corresponding implementation with the initializer and clean-up functions supplied as arguments.

At this point, PICOTM_STATE_TYPE() declares a variable of the state's type. State variables must be initialized with PICOTM_STATE_INITIALIZER.

The macro PICOTM_STATE_ACQUIRE() returns the state of a state variable. On it's first invocation, it runs the provided initializer function. Later invocations return the already initialized state; until the state is released with PICOTM_STATE_RELEASE(). This macro runs the provided clean-up function and releases the state.

struct picotm_error error = PICOTM_ERROR_INITIALIZER;
struct state* state = PICOTM_STATE_ACQUIRE(state, state_var, true, &error);
if (picotm_error_is_set(&error)) {
// perform error handling
}
// ...
// do something with 'state'
// ...
// In thread-local cleanup code
PICOTM_STATE_RELEASE(state, state_var);

State handling is not thread safe. For a thread-safe implemenation, PICOTM_SHARED_STATE() and its helpers are available.