Source · fairmq/tools/
Semaphore.cxxsource
1/********************************************************************************2 * Copyright (C) 2019 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH *3 * *4 * This software is distributed under the terms of the *5 * GNU Lesser General Public Licence (LGPL) version 3, *6 * copied verbatim in the file "LICENSE" *7 ********************************************************************************/8 9#include "Semaphore.h"10 11namespace fair::mq::tools12{13 14Semaphore::Semaphore()15 : Semaphore(0)16{}17 18Semaphore::Semaphore(std::size_t initial_count)19 : fCount(initial_count)20{}21 22auto Semaphore::Wait() -> void23{24 std::unique_lock<std::mutex> lk(fMutex);25 if (fCount > 0) {26 --fCount;27 } else {28 fCv.wait(lk, [this] { return fCount > 0; });29 --fCount;30 }31}32 33auto Semaphore::Signal() -> void34{35 std::unique_lock<std::mutex> lk(fMutex);36 ++fCount;37 lk.unlock();38 fCv.notify_one();39}40 41auto Semaphore::GetCount() const -> std::size_t42{43 std::unique_lock<std::mutex> lk(fMutex);44 return fCount;45}46 47SharedSemaphore::SharedSemaphore()48 : fSemaphore(std::make_shared<Semaphore>())49{}50 51SharedSemaphore::SharedSemaphore(std::size_t initial_count)52 : fSemaphore(std::make_shared<Semaphore>(initial_count))53{}54 55auto SharedSemaphore::Wait() -> void56{57 fSemaphore->Wait();58}59 60auto SharedSemaphore::Signal() -> void61{62 fSemaphore->Signal();63}64 65auto SharedSemaphore::GetCount() const -> std::size_t66{67 return fSemaphore->GetCount();68}69 70} // namespace fair::mq::tools