Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
f6e70839466e5eac768530791dcb7943bc9bed53
[simgrid.git] / src / xbt / OsSemaphore.hpp
1 /* Copyright (c) 2019. 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 <condition_variable>
7 #include <mutex>
8
9 namespace simgrid {
10 namespace xbt {
11 class XBT_PUBLIC OsSemaphore {
12 public:
13   explicit inline OsSemaphore(unsigned int capa) : capa_(capa) {}
14
15   inline void acquire()
16   {
17     std::unique_lock<std::mutex> lock(mutex_);
18     condition_.wait(lock, [this]() { return capa_ > 0; });
19     --capa_;
20   }
21
22   inline void release()
23   {
24     std::unique_lock<std::mutex> lock(mutex_);
25     ++capa_;
26     condition_.notify_one();
27   }
28
29 private:
30   unsigned int capa_;
31   std::mutex mutex_;
32   std::condition_variable condition_;
33 };
34 } // namespace xbt
35 } // namespace simgrid