Remove dynamic exceptions
[anna.git] / source / core / mt / Mutex.cpp
1 // ANNA - Anna is Not Nothingness Anymore                                                         //
2 //                                                                                                //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo                         //
4 //                                                                                                //
5 // See project site at http://redmine.teslayout.com/projects/anna-suite                           //
6 // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
7
8
9 #include <pthread.h>
10 #include <errno.h>
11
12 #include <anna/core/mt/Mutex.hpp>
13 #include <anna/config/defines.hpp>
14
15 using namespace anna;
16
17 Mutex::Mutex(const Mutex::Mode::_v mode) {
18 #ifdef _MT
19
20   if(mode == Mode::Recursive) {
21     pthread_mutexattr_t mattr;
22     pthread_mutexattr_init(&mattr);
23     pthread_mutexattr_settype(&mattr, PTHREAD_MUTEX_RECURSIVE_NP);  // PTHREAD_MUTEX_RECURSIVE in Solaris
24     pthread_mutex_init(&a_id, &mattr);
25     pthread_mutexattr_destroy(&mattr);
26   } else
27     pthread_mutex_init(&a_id, NULL);
28
29 #endif
30 }
31
32 Mutex::~Mutex() {
33 #ifdef _MT
34   pthread_mutex_destroy(&a_id);
35 #endif
36 }
37
38 void Mutex::lock()
39 noexcept(false) {
40 #ifdef _MT
41   int errorCode;
42
43   if((errorCode = pthread_mutex_lock(&a_id)) != 0)
44     throw RuntimeException(std::string("pthread_mutex_lock"), errorCode, ANNA_FILE_LOCATION);
45
46 #endif
47 }
48
49 void Mutex::unlock()
50 {
51 #ifdef _MT
52   int errorCode;
53
54   try {
55     if((errorCode = pthread_mutex_unlock(&a_id)) != 0)
56       throw RuntimeException(std::string("pthread_mutex_unlock"), errorCode, ANNA_FILE_LOCATION);
57   } catch(Exception& ex) {
58     ex.trace();
59   }
60
61 #endif
62 }
63
64 bool Mutex::trylock()
65 noexcept(false) {
66 #ifdef _MT
67   int errorCode;
68
69   try {
70     if((errorCode = pthread_mutex_trylock(&a_id)) != 0) {
71       if(errorCode == EBUSY)
72         return false;
73
74       throw RuntimeException(std::string("pthread_mutex_trylock"), errorCode, ANNA_FILE_LOCATION);
75     }
76   } catch(Exception& ex) {
77     ex.trace();
78   }
79
80 #endif
81   return true;
82 }
83
84