Updated license
[anna.git] / source / core / mt / Thread.cpp
1 // ANNA - Anna is Not Nothingness Anymore
2 //
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
4 //
5 // https://bitbucket.org/testillano/anna
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 //     * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 //     * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
16 // distribution.
17 //     * Neither the name of Google Inc. nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
20 //
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 //
33 // Authors: eduardo.ramos.testillano@gmail.com
34 //          cisco.tierra@gmail.com
35
36
37 #include <unistd.h>
38 #include <signal.h>
39
40 #include <anna/core/functions.hpp>
41 #include <anna/core/tracing/TraceMethod.hpp>
42 #include <anna/core/tracing/TraceFunction.hpp>
43 #include <anna/core/tracing/Logger.hpp>
44 #include <anna/core/mt/Runnable.hpp>
45 #include <anna/core/mt/Thread.hpp>
46 #include <anna/core/mt/ThreadManager.hpp>
47
48 using namespace std;
49 using namespace anna;
50
51 Thread::~Thread() {
52 #ifdef _MT
53
54   if(isRunning() == true) {
55     LOGWARNING(
56       string msg(asString());
57       msg += " | Destroying active thread";
58       Logger::warning(msg, ANNA_FILE_LOCATION);
59     );
60 //      pthread_cancel (a_id);
61     a_id = (pthread_t) - 1;
62   }
63
64 #endif
65 }
66
67 void Thread::start(Runnable& runnable)
68 throw(RuntimeException) {
69   if(isRunning() == true) {
70     std::string msg(asString());
71     msg += " | Already activated";
72     throw RuntimeException(msg, ANNA_FILE_LOCATION);
73   }
74
75   a_data.thread = this;
76   a_data.runnable = &runnable;
77 #ifdef _MT
78   pthread_attr_t attr;
79   pthread_attr_init(&attr);
80
81   if(isJoinable() == false)
82     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
83
84   int errorCode;
85
86   if((errorCode = pthread_create(&a_id, &attr, Thread::exec, &a_data)) != 0) {
87     if(a_data.thread->a_manager != NULL)
88       a_data.thread->a_manager->releaseThread(a_data.thread);
89
90     throw RuntimeException(std::string("Thread::start"), errorCode, ANNA_FILE_LOCATION);
91   }
92
93 #else
94   exec(&a_data);
95 #endif
96 }
97
98 void Thread::join()
99 throw(RuntimeException) {
100 #ifdef _MT
101   int errorCode;
102   const pthread_t self(pthread_self());
103
104   if(pthread_equal(a_id, self) != 0) {
105     string msg("Thread::join | ");
106     msg += asString();
107     msg += " | Cannot call join from itself";
108     throw RuntimeException(msg, ANNA_FILE_LOCATION);
109   }
110
111   if((errorCode = pthread_join(a_id, NULL)) != 0)
112     throw RuntimeException(std::string("Thread::join"), errorCode, ANNA_FILE_LOCATION);
113
114 #endif
115 }
116
117 /* Código correspondiente al thread */
118 void* Thread::exec(void* arg) {
119   WHEN_MULTITHREAD(
120     sigset_t mask;
121     sigemptyset(&mask);
122     pthread_sigmask(SIG_SETMASK, &mask, NULL);
123   );
124   Data* data = reinterpret_cast <Data*>(arg);
125   LOGDEBUG(
126     string msg("Starting thread | ");
127     msg += data->thread->asString();
128     msg += data->runnable->asString();
129     Logger::debug(msg, ANNA_FILE_LOCATION);
130   );
131
132   try {
133     data->runnable->initialize();
134     data->runnable->setIsRunning(true);
135     data->runnable->run();
136     data->runnable->setIsRunning(false);
137     LOGDEBUG(
138       string msg("Finishing thread | ");
139       msg += data->thread->asString();
140       msg += data->runnable->asString();
141       Logger::debug(msg, ANNA_FILE_LOCATION);
142     );
143     data->runnable->terminate();
144   } catch(Exception& ex) {
145     data->runnable->setIsRunning(false);
146     LOGDEBUG(
147       string msg("Finishing thread | ");
148       msg += data->thread->asString();
149       msg += data->runnable->asString();
150       Logger::debug(msg, ANNA_FILE_LOCATION);
151     );
152     data->runnable->terminate();
153     ex.trace();
154   }
155
156   data->thread->a_id = (pthread_t) - 1;
157
158   if(data->thread->a_manager != NULL)
159     data->thread->a_manager->releaseThread(data->thread);
160
161   return NULL;
162 }
163
164 std::string Thread::asString() const
165 throw() {
166   std::string result("anna::Thread { Id: ");
167   result += functions::asHexString((int) a_id);
168   result += functions::asString(" | Flags (0x%x): ", a_flags);
169   result += (isJoinable()) ? "Joinable" : "None";
170   result += " | Running: ";
171   result += functions::asString(isRunning());
172   result += " | ThreadManager: ";
173
174   if(a_manager == NULL)
175     result += "<none>";
176   else
177     result += a_manager->getName();
178
179   return result += " }";
180 }
181