Remove dynamic exceptions
[anna.git] / source / core / mt / Semaphore.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
11 #include <anna/core/mt/Semaphore.hpp>
12 #include <anna/core/RuntimeException.hpp>
13 #include <anna/core/functions.hpp>
14 #include <anna/config/defines.hpp>
15
16 using namespace anna;
17
18 Semaphore::Semaphore(unsigned int count) :
19   Safe() {
20 #ifdef _MT
21   sem_init(&a_id, 0, count);
22 #endif
23 }
24
25 Semaphore::~Semaphore() {
26 #ifdef _MT
27   sem_destroy(&a_id);
28 #endif
29 }
30
31 void Semaphore::wait()
32 noexcept(false) {
33 #ifdef _MT
34   int errorCode;
35   anna_signal_shield(errorCode, sem_wait(&a_id));
36
37   if(errorCode != 0)
38     throw RuntimeException(std::string("Error doing wait"), errno, ANNA_FILE_LOCATION);
39
40 #endif
41 }
42
43 bool Semaphore::tryWait()
44 noexcept(false) {
45   bool result(true);
46 #ifdef _MT
47   int errorCode;
48
49   if((errorCode = sem_trywait(&a_id)) != 0) {
50     if(errorCode != EBUSY)
51       throw RuntimeException(std::string("Error trying wait"), errno, ANNA_FILE_LOCATION);
52     else
53       result = false;
54   }
55
56 #endif
57   return result;
58 }
59
60 void Semaphore::signal()
61 noexcept(false) {
62 #ifdef _MT
63   int errorCode = sem_post(&a_id);
64
65   if(errorCode != 0)
66     throw RuntimeException(std::string("Error doing post"), errno, ANNA_FILE_LOCATION);
67
68 #endif
69 }
70
71 std::string Semaphore::asString() const
72 {
73   std::string msg("anna::Semaphone { Id: ");
74   msg += functions::asHexString(anna_ptrnumber_cast(&a_id));
75   msg += " | Value: ";
76 #ifdef _MT
77   int value = 0;
78   sem_getvalue(&(const_cast <Semaphore*>(this)->a_id), &value);
79   msg += functions::asString(value);
80 #else
81   msg += "<none>";
82 #endif
83   return msg += " }";
84 }
85