Final Platform Layer 0.9.8-beta
Loading...
Searching...
No Matches
Mutexes

Overview

This section explains how to create and handling of 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.

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.

if (!fplMutexInit(&mutex)) {
// Error: Mutex failed initializing -> Too many active mutexes for this process or already initialized
}
// ... Mutex is not required anymore
fpl_platform_api bool fplMutexInit(fplMutexHandle *mutex)
Initializes the given mutex.
fpl_platform_api void fplMutexDestroy(fplMutexHandle *mutex)
Releases the given mutex and clears the structure to zero.
The mutex handle structure.

Locking/Unlocking a Mutex

Locking a Mutex

Call fplMutexLock() with a pointer to fplMutexHandle as an argument, to lock a Mutex.
It 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
fplMutexLock(&mutex);
{
// Do something in this critical section here
}
// Locking a mutex can fail, so ensure that you check the result
if (fplMutexLock(&mutex)) {
// Do something in this critical section here
fplMutexUnlock(&mutex);
}
// Dont wait for the mutex to be unlocked, just try to lock it
if (fplMutexTryLock(&mutex)) {
// Do something in this critical section here
fplMutexUnlock(&mutex);
}
fpl_platform_api bool fplMutexUnlock(fplMutexHandle *mutex)
Unlocks the given mutex.
fpl_platform_api bool fplMutexLock(fplMutexHandle *mutex)
Locks the given mutex and blocks any other threads.
fpl_platform_api bool fplMutexTryLock(fplMutexHandle *mutex)
Tries to lock the given mutex without blocking other threads.
Note
It is recommended to put an opening/closing brace to mark the code inside the lock as critical code.