Macros
picotm-lib-shared-state.h File Reference

Contains shared-state helper macros. More...

#include <stddef.h>
#include "compiler.h"
#include "picotm-lib-ptr.h"
#include "picotm-lib-shared-ref-obj.h"

Macros

#define PICOTM_SHARED_STATE(_name, _type)
 
#define PICOTM_SHARED_STATE_INITIALIZER
 
#define PICOTM_SHARED_STATE_REF(_name, _self, _error)
 
#define PICOTM_SHARED_STATE_STATIC_IMPL(_name, _type, _init, _uninit)
 
#define PICOTM_SHARED_STATE_TYPE(_name)
 
#define PICOTM_SHARED_STATE_UNREF(_name, _self)
 

Detailed Description

Picotm provides a number of helper macros to automate management of shared state. The state is stored in an additional structure, of which threads can acquire and release references.

The macro PICOTM_SHARED_STATE() declares shared state. It receives the name and the type of the shared state and expands to a type definition. For this type, the macro PICOTM_SHARED_STATE_STATIC_IMPL() generates an implementation. For the first and final reference to the shared state, the generated code invokes an initializer or clean-up function. both are given as arguments to PICOTM_SHARED_STATE_STATIC_IMPL(). The example below illustrates this for a state of type struct shared.

struct shared {
int data1;
int data2;
};
void
init_shared_fields(struct shared* shared, struct picotm_error* error)
{
shared->data1 = 0;
shared->data2 = 0;
}
void
uninit_shared_fields(struct shared* shared)
{
// nothing to do
}
PICOTM_SHARED_STATE(shared, struct shared);
init_shared_fields,
uninit_shared_fields)

A shared-state variable is declared with PICOTM_SHARED_STATE_TYPE(). It has to be initalized by assigning PICOTM_SHARED_STATE_INITIALIZER.

A call to PICOTM_SHARED_STATE_REF() acquires a reference, a call to PICOTM_SHARED_STATE_UNREF() releases a previously acquired reference. For convenience, PICOTM_SHARED_STATE_REF() returns a pointer to the shared state.

struct picotm_error error = PICOTM_ERROR_INITIALIZER;
struct shared* shared =
PICOTM_SHARED_STATE_REF(shared, &shared_var, &error);
if (picotm_error_is_set(&error)) {
// perform error handling
}
// ...
// do something with 'shared'
// ...
// In thread-local cleanup code
PICOTM_SHARED_STATE_UNREF(shared, &shared_var);

Acquiring and releasing a reference to a shared state is thread-safe. Both calls are serialized with each other and the provided initializer and clean-up functions. Accessing the shared-state data fields requires additional concurrency control.