GCS  0.2.3
gu_lock.hpp
1 /*
2  * Copyright (C) 2009 Codership Oy <info@codership.com>
3  *
4  */
5 
6 #ifndef __GU_LOCK__
7 #define __GU_LOCK__
8 
9 #include <pthread.h>
10 #include <cerrno>
11 
12 #include "gu_exception.hpp"
13 #include "gu_logger.hpp"
14 #include "gu_mutex.hpp"
15 #include "gu_cond.hpp"
16 #include "gu_datetime.hpp"
17 
18 namespace gu
19 {
20  class Lock
21  {
22  pthread_mutex_t* const value;
23 
24  Lock (const Lock&);
25  Lock& operator=(const Lock&);
26 
27  public:
28 
29  Lock (const Mutex& mtx) : value(&mtx.value)
30  {
31 
32  int err = pthread_mutex_lock (value);
33  if (gu_unlikely(err))
34  {
35  std::string msg = "Mutex lock failed: ";
36  msg = msg + strerror(err);
37  throw Exception(msg.c_str(), err);
38  }
39  }
40 
41  virtual ~Lock ()
42  {
43  int err = pthread_mutex_unlock (value);
44  if (gu_unlikely(err))
45  {
46  log_fatal << "Mutex unlock failed: " << err << " ("
47  << strerror(err) << "), Aborting.";
48  ::abort();
49  }
50  // log_debug << "Unlocked mutex " << value;
51  }
52 
53  inline void wait (const Cond& cond)
54  {
55  cond.ref_count++;
56  pthread_cond_wait (&(cond.cond), value);
57  cond.ref_count--;
58  }
59 
60  inline void wait (const Cond& cond, const datetime::Date& date)
61  {
62  timespec ts;
63 
64  date._timespec(ts);
65  cond.ref_count++;
66  int ret = pthread_cond_timedwait (&(cond.cond), value, &ts);
67  cond.ref_count--;
68 
69  if (gu_unlikely(ret)) gu_throw_error(ret);
70  }
71  };
72 }
73 
74 #endif /* __GU_LOCK__ */
Definition: gu_lock.hpp:20
Definition: gu_mutex.hpp:19
Definition: gu_cond.hpp:19
void _timespec(timespec &ts) const
Definition: gu_datetime.hpp:180
Definition: gu_exception.hpp:19
Date/time representation.
Definition: gu_datetime.hpp:115