Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add new entry in Release_Notes.
[simgrid.git] / src / xbt / OsSemaphore.hpp
1 /* Copyright (c) 2019-2023. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include <xbt/base.h>
7
8 #include <condition_variable>
9 #include <mutex>
10
11 namespace simgrid::xbt {
12 class XBT_PUBLIC OsSemaphore {
13 public:
14   explicit inline OsSemaphore(unsigned int capa) : capa_(capa) {}
15
16   inline void acquire()
17   {
18     std::unique_lock lock(mutex_);
19     condition_.wait(lock, [this]() { return capa_ > 0; });
20     --capa_;
21   }
22
23   inline void release()
24   {
25     const std::scoped_lock lock(mutex_);
26     ++capa_;
27     condition_.notify_one();
28   }
29
30 private:
31   unsigned int capa_;
32   std::mutex mutex_;
33   std::condition_variable condition_;
34 };
35 } // namespace simgrid::xbt