GCS  0.2.3
gu_mutex.hpp
1 /*
2  * Copyright (C) 2009 Codership Oy <info@codership.com>
3  *
4  */
5 
6 #ifndef __GU_MUTEX__
7 #define __GU_MUTEX__
8 
9 #include <pthread.h>
10 #include <cerrno>
11 #include <cstring>
12 
13 #include "gu_macros.h"
14 #include "gu_mutex.h"
15 #include "gu_throw.hpp"
16 
17 namespace gu
18 {
19  class Mutex
20  {
21  public:
22 
23  Mutex () : value()
24  {
25  gu_mutex_init (&value, NULL); // always succeeds
26  }
27 
28  ~Mutex ()
29  {
30  int err = gu_mutex_destroy (&value);
31  if (gu_unlikely(err != 0))
32  {
33  gu_throw_error (err) << "pthread_mutex_destroy()";
34  }
35  }
36 
37  void lock()
38  {
39  gu_mutex_lock(&value);
40  }
41 
42  void unlock()
43  {
44  gu_mutex_unlock(&value);
45  }
46 
47  protected:
48 
49  gu_mutex_t mutable value;
50 
51  private:
52 
53  Mutex (const Mutex&);
54  Mutex& operator= (const Mutex&);
55 
56  friend class Lock;
57  };
58 
60  {
61  public:
62  RecursiveMutex() : mutex_()
63  {
64  pthread_mutexattr_t mattr;
65  pthread_mutexattr_init(&mattr);
66  pthread_mutexattr_settype(&mattr, PTHREAD_MUTEX_RECURSIVE);
67  pthread_mutex_init(&mutex_, &mattr);
68  pthread_mutexattr_destroy(&mattr);
69  }
70 
72  {
73  pthread_mutex_destroy(&mutex_);
74  }
75 
76  void lock()
77  {
78  if (pthread_mutex_lock(&mutex_)) gu_throw_fatal;
79  }
80 
81  void unlock()
82  {
83  if (pthread_mutex_unlock(&mutex_)) gu_throw_fatal;
84  }
85 
86  private:
88  void operator=(const RecursiveMutex&);
89 
90  pthread_mutex_t mutex_;
91  };
92 
93 
94 }
95 
96 #endif /* __GU_MUTEX__ */
Definition: gu_mutex.hpp:59
Definition: gu_lock.hpp:20
Definition: gu_mutex.hpp:19