#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& operator=(const Semaphore&) = delete; Queue waiting; public: /*! \brief Constructor; initialized the counter with provided value `c` * \param c Initial counter value */ explicit Semaphore(unsigned c = 0) : counter(c) {} unsigned counter; /*! \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); };