sttcl  v0.9c
STTCL C++ template state machine framework
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
SttclCx11Semaphore.h
Go to the documentation of this file.
1 
25 #ifndef STTCLCX11SEMAPHORE_H_
26 #define STTCLCX11SEMAPHORE_H_
27 
28 #if defined(STTCL_CX11_THREADS) or defined(STTCL_CX11_IMPL)
29 #include <mutex>
30 #include <condition_variable>
31 #include <locale>
32 
33 #include "../include/SttclTime.h"
34 
35 namespace sttcl
36 {
37 
38 namespace internal
39 {
40 namespace cx11_impl
41 {
42 class Cx11SemaphoreSurrogate {
43  private:
44  std::mutex mMutex;
45  std::condition_variable v;
46  int mV;
47  public:
48  Cx11SemaphoreSurrogate(int v): mV(v){}
49  void post(int count=1){
50  std::unique_lock<std::mutex> lock(mMutex);
51  mV+=count;
52  if (mV > 0) v.notify_all();
53  }
54  void wait(int count = 1){
55  std::unique_lock<std::mutex> lock(mMutex);
56  mV-= count;
57  while (mV < 0)
58  v.wait(lock);
59  }
60  template<typename T>
61  bool try_wait(int count = 1, T duration = T()){
62  std::unique_lock<std::mutex> lock(mMutex);
63  mV-= count;
64  while (mV < 0)
65  {
66  if (v.wait_for(lock,duration) == std::cv_status::timeout)
67  {
68  mV+= count;
69  return false;
70  }
71  }
72  return true;
73  }
74  };
78 class SttclCx11Semaphore
79 {
80 public:
81  typedef Cx11SemaphoreSurrogate NativeSemaphoreType;
82  SttclCx11Semaphore(unsigned int initialCount);
83  virtual ~SttclCx11Semaphore();
84 
85  void wait();
86  bool try_wait(const TimeDuration<>& timeout);
87  void post();
88 
89 private:
90  NativeSemaphoreType semaphore;
91 };
92 
93 }
94 }
95 }
96 #endif
97 #endif /* STTCLCX11SEMAPHORE_H_ */