Files
bsb2/kernel/sync/semaphore.h
2026-01-05 10:41:27 +01:00

56 lines
1.4 KiB
C++

#pragma once
#include "../object/queue.h"
#include "../types.h"
/*! \file
* \brief \ref Semaphore for synchronization of threads.
*/
/*!
* \defgroup ipc Inter-Process Communication
* \brief Communication between threads
*/
// Forward declarations to break cyclic includes
struct Vault;
class Thread;
/*! \brief Semaphore used for synchronization of threads.
* \ingroup ipc
*
* The class Semaphore implements the concept of counting semaphores.
* Waiting threads are parked inside a \ref Queue.
*/
class Semaphore {
// Prevent copies and assignments
Semaphore(const Semaphore&) = delete;
Semaphore(Semaphore&&) = delete;
Semaphore& operator=(const Semaphore&) = delete;
Semaphore& operator=(Semaphore&&) = delete;
unsigned counter;
Queue<Thread> waiting;
public:
/*! \param init Initial counter value
*/
explicit Semaphore(unsigned init = 0) : counter(init) {}
~Semaphore() = default;
/*! \brief Wait for access to the critical area.
*
* Enter/decrement/wait operation: If the counter is greater than 0, then
* it is decremented by one. Otherwise the calling thread will be enqueued
* to wait until it can do that.
*
*/
void p(Vault& vault);
/*! \brief Leave the critical area.
*
* Leave/increment operation: If there are threads waiting, wake the
* first one; otherwise increment the counter by one.
*
*/
void v(Vault& vault);
};