Final Platform Layer 0.9.8-beta
No Matches


This section explains how to create and manage semaphores.
Semaphores are similar to Mutexes but have one major difference: Any Thread can release it!
It internally uses an atomic counter which gets incremented and decremented.

Initialize a Semaphore

Call fplSemaphoreInit() to initialize a Semaphore with a fplSemaphoreHandle as an argument. Also, you need to specify the initial value for the Semaphore to start with.
Call fplSemaphoreDestroy() when you are done with that Semaphore to let it releases its internal resources.

if (!fplSemaphoreInit(&semaphore, 1)) {
// Error: Semaphore failed to initialize -> This will most likely never happen
// ... Semaphore is not required anymore and no threads are waiting on it
fpl_platform_api void fplSemaphoreDestroy(fplSemaphoreHandle *semaphore)
Releases the internal semaphore resources.
fpl_platform_api bool fplSemaphoreInit(fplSemaphoreHandle *semaphore, const uint32_t initialValue)
Initializes the semaphore with the given initial value.
The semaphore handle structure.

Waiting/Locking a Semaphore

Call fplSemaphoreWait() to let a Thread wait and decrement the Semaphores value with a fplSemaphoreHandle as an argument.
If the Semaphores value is greater than zero, then the decrement will happen and the function returns immediately.
If the Semaphores value is zero then the Thread will wait until it is possible to decrement the value.
Also, you need to specify the number of milliseconds you want the thread to wait. If FPL_TIMEOUT_INFINITE is passed, it will wait forever.

// Wait until the Semaphores value is > 0
// ... or
// Wait at max for 5 seconds to the Semaphores value to be > 0
fplSemaphoreWait(&semaphore, 5000);
fpl_platform_api bool fplSemaphoreWait(fplSemaphoreHandle *semaphore, const fplTimeoutValue timeout)
Waits for the semaphore until it gets signaled or the timeout has been reached.
Infinite timeout constant.

Waiting on multiple Semaphores?

A thread can only wait on one single Semaphore at a time - if you need to wait on multiple Semaphores, you should consider using Signals .

Trying to wait on a Semaphore

fplSemaphoreTryWait() is the same as fplSemaphoreWait() , except that if the decrement cannot immediately perform, the current thread will not be blocked.

Releasing the Semaphore

Call fplSemaphoreRelease() with the fplSemaphoreHandle in question, to release a Semaphore and signal all waiting Threads.

// Release a Semaphore and signal all waiting Threads
fpl_platform_api bool fplSemaphoreRelease(fplSemaphoreHandle *semaphore)
Increments the semaphore value by one.

Reading the Value from the Semaphore

Call fplSemaphoreValue() to get the current value from the Semaphore.

int32_t currentValue = fplSemaphoreValue(&semaphore);
// ... do something with the value here
fpl_platform_api int32_t fplSemaphoreValue(fplSemaphoreHandle *semaphore)
Gets the current semaphore value.