RTXI  2.4
The Real-Time eXperiment Interface Documentation
mutex.cpp
Go to the documentation of this file.
1 /*
2  The Real-Time eXperiment Interface (RTXI)
3  Copyright (C) 2011 Georgia Institute of Technology, University of Utah, Weill Cornell Medical College
4 
5  This program is free software: you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation, either version 3 of the License, or
8  (at your option) any later version.
9 
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  GNU General Public License for more details.
14 
15  You should have received a copy of the GNU General Public License
16  along with this program. If not, see <http://www.gnu.org/licenses/>.
17 
18 */
19 
20 #include <mutex.h>
21 #include <rt.h>
22 
24 {
25  if (mutex)
26  mutex->lock();
27 }
28 
30 {
31  if (mutex)
32  mutex->unlock();
33 }
34 
36 {
37  pthread_mutexattr_t attr;
38  pthread_mutexattr_init(&attr);
39 
40  switch (type)
41  {
42  case RECURSIVE:
43  pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE_NP);
44  break;
45  default:
46  pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_FAST_NP);
47  }
48 
49  pthread_mutex_init(&mutex,&attr);
50  pthread_mutexattr_destroy(&attr);
51 }
52 
54 {
55  pthread_mutex_destroy(&mutex);
56 }
57 
58 void Mutex::lock(void)
59 {
60 #ifdef DEBUG
61  if (RT::OS::isRealtime())
62  {
63  ERROR_MSG("Detected unsafe lock attempt in RT thread\n");
64  if (!tryLock())
65  ERROR_MSG("Failed to obtain the lock\n");
66  return;
67  }
68 #endif // DEBUG
69 
70  pthread_mutex_lock(&mutex);
71 }
72 
73 void Mutex::unlock(void)
74 {
75  pthread_mutex_unlock(&mutex);
76 }
77 
78 bool Mutex::tryLock(void)
79 {
80  return pthread_mutex_trylock(&mutex) == 0;
81 }
Mutex::RECURSIVE
@ RECURSIVE
Definition: mutex.h:59
ERROR_MSG
void ERROR_MSG(const std::string &errmsg,...)
Definition: debug.cpp:27
Mutex::lock
void lock(void)
Definition: mutex.cpp:58
Mutex::Mutex
Mutex(type_t type=FAST)
Definition: mutex.cpp:35
Mutex::Locker::~Locker
~Locker(void)
Definition: mutex.cpp:29
RT::OS::isRealtime
bool isRealtime(void)
Definition: rt_os-posix.cpp:136
Mutex::tryLock
bool tryLock(void)
Definition: mutex.cpp:78
Mutex::~Mutex
~Mutex(void)
Definition: mutex.cpp:53
Mutex::type_t
type_t
Definition: mutex.h:56
Mutex
Definition: mutex.h:28
Mutex::unlock
void unlock(void)
Definition: mutex.cpp:73
rt.h
mutex.h
Mutex::Locker::Locker
Locker(Mutex *m)
Definition: mutex.cpp:23