Skip to content

semaphore

Alairion edited this page May 8, 2021 · 5 revisions

Name

Defined in header <nes/semaphore.hpp>

class semaphore;

Description

nes::semaphore is a synchronization primitive that use a resource counter. When trying to acquire a resource, the calling thread is blocked until a resource is available. If you don't want to block a thread on acquire, then use try_acquire instead. To make a resource available, you have to increment the semaphore counter by calling release. All member functions are thread-safe.

Member types

Type Description
native_handle_type The underlying, implementation-defined, representation of a process

Public Member functions

Function Description
semaphore Constructs the semaphore object
~semaphore Destroys the semaphore object
operator= Deleted
acquire Waits until a resource is available, then decrements the resource counter
try_acquire Checks if a resource is available, and if that is the case decrements the resource counter
release Increments the resource counter
native_handle Returns the underlying, implementation-defined, representation of the semaphore

Example

#include <thread>
#include <iostream>
#include <array>

#include <nes/semaphore.hpp>

void another_thread(const std::array<std::uint64_t, 8>& data, nes::semaphore& semaphore)
{
    for(std::size_t i{}; i < 8; ++i)
    {
        //Wait until the next resource is available
        semaphore.acquire();
        //It is ready, display it
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    std::array<std::uint64_t, 8> data{0, 1};
    //Two resources are already available, so we create a semaphore with two resource
    nes::semaphore semaphore{2};

    std::thread thread{another_thread, std::cref(data), std::ref(semaphore)};

    for(std::size_t i{2}; i < 8; ++i)
    {
        //Compute something
        data[i] = i * i;
        //Increment the resource counter of the semaphore (unlock the other thread only once)
        semaphore.release();
    }

    if(thread.joinable())
        thread.join();
}

Output

0
1
4
9
16
25
36
49
Clone this wiki locally