Updated license
[anna.git] / include / anna / core / mt / Runnable.hpp
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 #ifndef anna_core_mt_Runnable_hpp
38 #define anna_core_mt_Runnable_hpp
39
40 #include <string>
41
42 #include <anna/core/functions.hpp>
43
44 #include <anna/core/RuntimeException.hpp>
45 #include <anna/core/mt/Mutex.hpp>
46
47 namespace anna {
48
49 class Thread;
50
51 /**
52    Clase generica para implementar clases que deben realizar una unica accion concreta y que puede ser
53    lanzada desde un Thread.
54 */
55 class Runnable : public Mutex {
56 public:
57   // Accesores
58   /**
59      Devuelve el nombre logico de esta instancia.
60      @return El nombre logico de esta instancia.
61   */
62   const std::string& getId() const throw() { return a_id; }
63
64   /**
65      Devuelve el valor del indicador de parada.
66      \return el valor del indicador de parada.
67      \warning La implementacion particular del metodo run deberia comprobar este valor
68      periodicamente.
69   */
70   bool hasRequestedStop() const throw() { return a_requestedStop == true; }
71
72   /**
73      Devuelve \em true si la instancia esta en ejecucion dentro de su propio thread o \em false en otro caso.
74      \return \em true si la instancia esta en ejecucion dentro de su propio thread o \em false en otro caso.
75   */
76   bool isRunning() const throw() { return a_isRunning; }
77
78   /**
79      Solicita la parada de esta instancia.
80   */
81   void requestStop() throw(RuntimeException);
82
83   /**
84      Devuelve una cadena con la informacion relevante de este objeto.
85      \return Una cadena con la informacion relevante de este objeto.
86   */
87   virtual std::string asString() const
88   throw() {
89     std::string result("anna::Runnable { Id: ");
90     result += a_id;
91     result += functions::asText(" | Running: ", a_isRunning);
92     result += functions::asText(" | RequestedStop: ", a_requestedStop);
93     return result += " }";
94   }
95
96 protected:
97   /**
98      Constructor.
99   */
100   Runnable() : a_id("<none>"), a_requestedStop(false), a_isRunning(false) {;}
101
102   /**
103     Constructor.
104     @param id Nombre logico de esta instancia.
105   */
106   Runnable(const std::string& id) : a_id(id), a_requestedStop(false), a_isRunning(false) {;}
107
108   /**
109     Constructor.
110     @param id Nombre logico de esta clase.
111   */
112   Runnable(const char* id) : a_id(id), a_requestedStop(false), a_isRunning(false) {;}
113
114   /**
115      Establece el nombre logico de esta instancia.
116      \param id Nuevo nombre logico de esta instancia.
117   */
118   void setId(const std::string& id) throw() { a_id = id; }
119
120   /**
121      Establece el indicador que informa sobre si esta instancia esta en ejecucion o no.
122      \param isRunning Indicador que informa sobre si esta instancia esta en ejecucion.
123      \warning Uso interno. Se invoca automaticamente desde Thread.
124   */
125   void setIsRunning(const bool isRunning) throw() {  a_isRunning = isRunning; }
126
127   /**
128      Metodo que se debe reescribir para inicializar el contenido de la clase justo antes de comenzar
129      su ejecucion.
130   */
131   virtual void initialize() throw(RuntimeException) {;}
132
133   /**
134      Metodo que debe reescribir para realizar la accion concreta. Por defecto invocara do_action mientras
135      que no se invoque la metodo requestStop de la instancia.
136   */
137   virtual void run() throw(RuntimeException);
138
139   /**
140      Metodo que se debe reescribir para finalizar la ejecucion de esta instancia.
141      \warning La re-implementacion de este metodo siempre debera invocar a la implementacion
142      original que esta re-escribiiendo.
143   */
144   virtual void terminate() throw() { a_requestedStop = false; }
145
146   /**
147      Metodo indicado por Runnable::run en tanto en cuanto no se invoque a requestStop.
148   */
149   virtual void do_action() throw(RuntimeException) = 0;
150
151 private:
152   std::string a_id;
153   bool a_requestedStop;
154   bool a_isRunning;
155
156   friend class Thread;
157 };
158
159 #define anna_complete_runnable(Class) void do_action () throw () {;}
160
161 } //namespace anna
162
163 #endif
164