# Poco

# class SpinlockMutex

Library: Foundation
Package: Threading
Header: Poco/Mutex.h

## Description

A SpinlockMutex, implemented in terms of std::atomic_flag, as busy-wait mutual exclusion.

Spins adaptively: spin briefly, then yield, then sleep. This avoids burning CPU while still being fast for uncontended locks. On C++20, uses test() with relaxed ordering for efficient polling (avoids cache line bouncing), then test_and_set() with acquire only when the lock appears free.

While in some cases (eg. locking small blocks of code) busy-waiting may be an optimal solution, in many scenarios spinlock may not be the right choice (especially on single-core systems) - it is up to the user to choose the proper mutex type for their particular case.

Works with the ScopedLock class.

## Member Summary

Member Functions: lock, tryLock, unlock

## Types Aliases

### ScopedLock

using ScopedLock = Poco::ScopedLock < SpinlockMutex >;

### ScopedLockWithUnlock

using ScopedLockWithUnlock = Poco::ScopedLockWithUnlock < SpinlockMutex >;

## Constructors

### SpinlockMutex

SpinlockMutex();

Creates the SpinlockMutex.

## Destructor

### ~SpinlockMutex

~SpinlockMutex();

Destroys the SpinlockMutex.

## Member Functions

### lock

void lock();

Locks the mutex. Blocks if the mutex is held by another thread.

### lock

void lock(
long milliseconds
);

Locks the mutex. Blocks up to the given number of milliseconds if the mutex is held by another thread. Throws a TimeoutException if the mutex can not be locked within the given timeout.

### tryLock

bool tryLock();

Tries to lock the mutex. Returns immediately, false if the mutex is already held by another thread, true if the mutex was successfully locked.

### tryLock

bool tryLock(
long milliseconds
);

Locks the mutex. Blocks up to the given number of milliseconds if the mutex is held by another thread. Returns true if the mutex was successfully locked.

### unlock

void unlock();

Unlocks the mutex so that it can be acquired by other threads.