picotm  0.9.0
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...
 

Macros

#define PICOTM_SPINLOCK_INITIALIZER
 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;
spinlock_init(&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.

picotm_spinlock_lock(&lock);
// critical section
picotm_spinlock_unlock(&lock);

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
picotm_spinlock_unlock(&lock);
}

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.