task_semaphore - Melnytskyi/fast_task GitHub Wiki

Declaration

    class task_semaphore {
    public:
        task_semaphore() = default;

        void setMaxThreshold(size_t val);
        void lock();
        bool try_lock();
        bool try_lock_for(size_t milliseconds);
        bool try_lock_until(std::chrono::high_resolution_clock::time_point time_point);
        void release();
        void release_all();
        bool is_locked();
    };

Description

task_semaphore implements a semaphore synchronization primitive that controls access to a resource pool by multiple tasks. It allows a specified number of tasks to hold the semaphore simultaneously. If a task attempts to acquire the semaphore and the maximum threshold is reached, the task is blocked until another task releases the semaphore.

Functions

void setMaxThreshold(size_t val);

Sets the maximum threshold of the semaphore to val. This function resets the semaphore, releases all waiting tasks, and updates the maximum and current allowance of tasks that can acquire the semaphore simultaneously.

void lock();

Acquires the semaphore. If the maximum threshold is reached, the calling task is blocked until the semaphore is available.

void try_lock();

Attempts to acquire the semaphore without blocking. Returns true if successful; otherwise, returns false.

void try_lock_for(size_t milliseconds);

Attempts to acquire the semaphore, blocking for up to milliseconds if the semaphore is not immediately available. Returns true if the semaphore was acquired within the timeout period; otherwise, returns false.

void try_lock_until(std::chrono::high_resolution_clock::time_point time_point);

Attempts to acquire the semaphore, blocking until a specified time_point if the semaphore is not immediately available. Returns true if the semaphore was acquired before the timeout; otherwise, returns false.

void release();

Releases the semaphore, allowing another task to acquire it. If there are tasks waiting for the semaphore, one of them is unblocked.

void release_all();

Releases the semaphore for all waiting tasks and resets the current allowance to the maximum threshold.

bool is_locked();

Checks if the semaphore is currently locked (i.e., if its maximum threshold has been reached). Returns true if it is locked; otherwise, returns false.

Usage

#include "tasks.hpp"

fast_task::task_semaphore semaphore;

void task_function() {
    semaphore.lock(); // Attempt to acquire the semaphore
    //....
    semaphore.release(); // Release the semaphore when done
}

int main() {
    semaphore.setMaxThreshold(2); // Set the maximum number of tasks that can hold the semaphore to 2

    // Launch tasks that use the semaphore
    std::thread t1(task_function);
    std::thread t2(task_function);
    std::thread t3(task_function); // This task will block until one of the first two tasks releases the semaphore

    t1.join();
    t2.join();
    t3.join();

    return 0;
}