Skip to content

Semaphores

Finalspace edited this page May 29, 2026 · 2 revisions

Table of Contents

Overview

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.

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

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 release its internal resources.

 semaphore;
if (!(&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
(&semaphore);

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
(&semaphore, );

// ... or

// Wait at max for 5 seconds to the Semaphores value to be > 0
(&semaphore, 5000);

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 be performed immediately, 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
(&semaphore);

Reading the Value from the Semaphore

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

int32_t currentValue = (&semaphore);

// ... do something with the value here

Final Platform Layer

Pages

Topics

Data Structures

Clone this wiki locally