General IRI utilities
mutex.cpp
1 // Copyright (C) 2009-2010 Institut de Robòtica i Informàtica Industrial, CSIC-UPC.
2 // Author Sergi Hernandez (shernand@iri.upc.edu)
3 // All rights reserved.
4 //
5 // This file is part of iriutils
6 // iriutils is free software: you can redistribute it and/or modify
7 // it under the terms of the GNU Lesser General Public License as published by
8 // the Free Software Foundation, either version 3 of the License, or
9 // at your option) any later version.
10 //
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public License
17 // along with this program. If not, see <http://www.gnu.org/licenses/>.
18 
19 #include "mutex.h"
20 #include <cerrno>
21 #include <stdio.h>
22 #include "mutexexceptions.h"
23 
25 {
26  int error=0;
27 
28  if((error=pthread_mutex_init(&this->access,NULL))!=0)
29  {
30  /* handle exception */
31  throw CMutexException(_HERE_,"Impossible to create a new mutex object.\n");
32  }
33 }
34 
35 void CMutex::enter(void)
36 {
37  int error=0;
38 
39  if ((error=pthread_mutex_lock(&this->access))!=0 )
40  {
41  /* handle exception */
42  throw CMutexException(_HERE_,"Impossible to lock the mutex.\n");
43  }
44 }
45 
47 {
48  int error=0;
49 
50  if ((error=pthread_mutex_trylock(&this->access))!=0 )
51  {
52  if(error == EBUSY)
53  return false;
54  else
55  {
56  /* handle exception */
57  throw CMutexException(_HERE_,"Impossible to try to enter the mutex.\n");
58  }
59  }
60 
61  return true;
62 }
63 
64 void CMutex::exit(void)
65 {
66  int error=0;
67 
68  if ((error=pthread_mutex_unlock(&this->access))!=0 )
69  {
70  /* handle exception */
71  throw CMutexException(_HERE_,"Impossible to unlock the mutex.\n");
72  }
73 }
74 
76 {
77  int error=0;
78 
79  this->try_enter();
80  this->exit();
81  if((error=pthread_mutex_destroy(&this->access))!=0)
82  {
83  /* handle exception */
84  throw CMutexException(_HERE_,"Impossible to destroy the mutex.\n");
85  }
86 }
Mutual exclusion exception class.
CMutex()
default constructor
Definition: mutex.cpp:24
virtual ~CMutex()
default destructor
Definition: mutex.cpp:75
bool try_enter(void)
function to request access to the critical section and return if denied.
Definition: mutex.cpp:46
void exit(void)
function to release the critical section
Definition: mutex.cpp:64
void enter(void)
function to request access to the critical section
Definition: mutex.cpp:35