IBR-DTNSuite  0.10
Mutex.cpp
Go to the documentation of this file.
1 /*
2  * Mutex.cpp
3  *
4  * Copyright (C) 2011 IBR, TU Braunschweig
5  *
6  * Written-by: Johannes Morgenroth <morgenroth@ibr.cs.tu-bs.de>
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  */
21 
22 #include "ibrcommon/config.h"
23 #include "ibrcommon/thread/Mutex.h"
24 #include <errno.h>
25 
26 namespace ibrcommon
27 {
29  {
30  }
31 
33  {
34  pthread_mutexattr_init(&m_attr);
35  pthread_mutexattr_settype(&m_attr, type);
36  pthread_mutex_init(&m_mutex, &m_attr);
37  }
38 
40  {
41  pthread_mutex_destroy( &m_mutex );
42  pthread_mutexattr_destroy(&m_attr);
43  }
44 
46  {
47  int ret = pthread_mutex_trylock( &m_mutex );
48 
49  switch (ret)
50  {
51  case 0:
52  break;
53 
54  case EBUSY:
55  throw MutexException("The mutex could not be acquired because it was already locked.");
56  break;
57  }
58  }
59 
61  {
62  switch (pthread_mutex_lock( &m_mutex ))
63  {
64  case 0:
65  return;
66 
67 // case EINVAL:
68 // throw MutexException("The mutex was created with the protocol attribute having the value PTHREAD_PRIO_PROTECT and the calling thread's priority is higher than the mutex's current priority ceiling.");
69 
70  // The pthread_mutex_trylock() function will fail if:
71 
72  case EBUSY:
73  throw MutexException("The mutex could not be acquired because it was already locked.");
74 
75  // The pthread_mutex_lock(), pthread_mutex_trylock() and pthread_mutex_unlock() functions may fail if:
76 
77  case EINVAL:
78  throw MutexException("The value specified by mutex does not refer to an initialised mutex object.");
79 
80  case EAGAIN:
81  throw MutexException("The mutex could not be acquired because the maximum number of recursive locks for mutex has been exceeded.");
82 
83  // The pthread_mutex_lock() function may fail if:
84 
85  case EDEADLK:
86  throw MutexException("The current thread already owns the mutex.");
87 
88  // The pthread_mutex_unlock() function may fail if:
89 
90  case EPERM:
91  throw MutexException("The current thread does not own the mutex.");
92 
93  default:
94  throw MutexException("can not lock the mutex");
95  }
96  }
97 
99  {
100  if (0 != pthread_mutex_unlock( &m_mutex ))
101  {
102  throw MutexException("can not unlock mutex");
103  }
104  }
105 
106  MutexMock Mutex::_dummy;
107 
109  {
110  return _dummy;
111  }
112 }