Skip to content

Mutexes

Finalspace edited this page May 29, 2026 · 2 revisions

Table of Contents

Overview

This section explains how to create and handle Mutexes.

A mutex is a Kernel-Level object used to prevent race conditions when multiple Threads access the same code section.

With a Mutex, you can ensure that only one thread at a time can access a code section.

See Synchronization methods for a comparison with the other synchronization primitives.

Initialize a Mutex

Call fplMutexInit() with a pointer to fplMutexHandle argument, to initialize a Mutex.

After the initialization is done, you can start locking and unlocking it.

When you are done with the Mutex call fplMutexDestroy() to release its internal resources.

 mutex;
if (!(&mutex)) {
    // Error: Mutex failed initializing -> Too many active mutexes for this process or already initialized
}

// ... Mutex is not required anymore
(&mutex);

Locking/Unlocking a Mutex

Locking a Mutex

Call fplMutexLock() with a pointer to fplMutexHandle as an argument, to lock a Mutex.

If this Mutex is already locked, the current thread will wait forever until it gets unlocked by the owner Thread.

If this Mutex is not locked yet, it will be locked by the calling Thread.

Note: You should always unlock the

fplMutexHandle as soon as possible - on the same call stack.

Unlocking a Mutex

Call fplMutexUnlock() with a pointer to fplMutexHandle as an argument, to unlock a Mutex.

The Mutex will be unlocked only when this function is called from the owner Thread.

If this Mutex was not locked or the owner Thread does not match it will fail.

Trying to lock a Mutex

Call fplMutexTryLock() with a pointer to fplMutexHandle as an argument, to try to lock a Mutex.

If the Mutex is already locked, the current thread will not be blocked and the function returns false.

If this Mutex is not locked yet, it will be locked by the calling Thread.

Example

// Lock down the execution of a code section to one Thread at a time
(&mutex);
{
    // Do something in this critical section here
}
(&mutex);

// Locking a mutex can fail, so ensure that you check the result
if ((&mutex)) {
    // Do something in this critical section here
    (&mutex);
}

// Don't wait for the mutex to be unlocked, just try to lock it
if ((&mutex)) {
    // Do something in this critical section here
    (&mutex);
}

Note: It is recommended to put an opening/closing brace to mark the code inside the lock as critical code.

Final Platform Layer

Pages

Topics

Data Structures

Clone this wiki locally