Data Structures | Macros
picotm-lib-spinlock.h File Reference

Contains struct picotm_spinlock and helper functions. More...

#include <assert.h>
#include <stdatomic.h>
#include "compiler.h"

Data Structures

struct  picotm_spinlock
 Provides an operating-system-neutral, non-recursive spin-lock type. More...


 Initializer macro for picotm spin locks.

Detailed Description

The struct picotm_spinlock data structure provides an spin lock that is independent from the operating system. It's useful for portable modules or creating more complex data structures.

The spin lock uses a very simple implementation. It's non-recursive, so a thread cannot acquire a spin lock twice at the same time. It's also not dead-lock safe. The advantage of the simple implmentation is that it cannot fail with an error.

An instance of struct picotm_spinlock is initialized by a call to picotm_spinlock_init().

struct picotm_spinlock lock;

Alternatively, the macro PICOTM_SPINLOCK_INITIALIZER initializes static lock variables, or stack-allocated locks. When both, function and macro initialization, is possible, the macro form os the prefered one.

After the initialization, the spinlock is in an unlocked state. A call to picotm_spinlock_lock() acquires the spin lock, and a call to picotm_spinlock_unlock() release the spin lock.

// critical section

A call to picotm_spinlock_lock() can possibly block the thread for an unbounded amount of time. A call to picotm_spinlock_try_lock() only tries once to acquire the lock, and returns a boolean value signalling success or failure.

if (picotm_spinlock_try_lock(&lock)) {
// critical section

The spin lock's locking and unlocking functions act as memory barriers. Therefore load and store operations before, within, or after a critical section take effect ontheir side of the respective barrier.