First commit
[anna.git] / include / anna / core / mt / ThreadManager.hpp
1 // ANNA - Anna is Not 'N' 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_ThreadManager_hpp
38 #define anna_core_mt_ThreadManager_hpp
39
40 #include <string>
41
42 #include <anna/core/mt/SafeRecycler.hpp>
43 #include <anna/core/mt/Thread.hpp>
44
45 #include <anna/core/core.hpp>
46
47 namespace anna {
48
49 class Semaphore;
50
51 /**
52    Gestor de threads. Optimiza la creacin y uso de los threads. Como ventaja adicional limita
53    el numero de threads que puede ser creados.
54 */
55 class ThreadManager : SafeRecycler <Thread> {
56 public:
57   /**
58      Modos de funcionamiento
59      \see ThreadManager
60   */
61   struct Mode {
62     enum _v {
63       None,
64       Unlimit, /**< Permite crear tantos threads como sea necesario. */
65       ExceptionWhenFull, /**< Si no hay ningun thread libre lanza una excepcion */
66       LockWhenFull /**< Si no hay ningun thread libre el metodo que invoca a #createThread queda
67          bloqueado hasta que algun otro thread termine su tarea. */
68     };
69
70     anna_declare_enum(Mode);
71   };
72
73   typedef iterator thread_iterator;
74
75   /**
76      Constructor.
77      @param name Nombre logico del la gestor de threads.
78      \param mode Modo de funcionamiento de ester gestor de threads.
79      @param maxSize Numero maximo de threads que seran creados.
80      \param flags Flags aplicados a los threads creados por este gestor.
81   */
82   ThreadManager(const char* name, const Mode::_v mode, const int maxSize, const int flags = Thread::Flag::None);
83
84   /**
85      Constructor.
86      Crea un gestor de thread que puede crecer con un número ilimitado de threads.
87      @param name Nombre logico del la gestor de threads.
88      \param flags Flags aplicados a los threads creados por este gestor.
89   */
90   ThreadManager(const char* name, const int flags = Thread::Flag::None);
91
92   /**
93      Destructor.
94   */
95   virtual ~ThreadManager();
96
97   /**
98    * Devuelve el nombre asociado a este gestor.
99    * \return el nombre asociado a este gestor.
100    */
101   const std::string& getName() const throw() { return a_name; }
102
103   /**
104      Obtiene la instancia de un thread. El thread sólo se liberará de forma automática cuando se termine la ejecución del mismo.
105      \return La instancia de un thread.
106
107      \warning Solo debe haber un único punto de creación de thread's por cada instancia de esta clase.
108   */
109   Thread* createThread() throw(RuntimeException);
110
111   /**
112    * Bloquea el proceso hasta que todos los threads lanzados por este gestor hayan terminado su ejecución.
113    * \warning \li No debería invocarse desde un thread que haya sido creado por este gestor.
114    *          \li Los threads deberían crearse con el flag Thread::Flag::Joinable.
115    */
116   void join() throw(RuntimeException);
117
118   /**
119      Devuelve un iterador al comienzo de la lista de threads.
120      \return un iterador al comienzo de la lista de threads.
121   */
122   thread_iterator thread_begin() throw() { return begin(); }
123
124   /**
125      Devuelve un iterador al final de la lista de threads.
126      \return un iterador al final de la lista de threads.
127   */
128   thread_iterator thread_end() throw() { return end(); }
129
130   /**
131      Devuelve el thread referenciado por el iterador recibido como parametro.
132      \param ii Iterador.
133      \return el thread referenciado por el iterador recibido como parametro.
134   */
135   static Thread* thread(thread_iterator ii) throw() { return SafeRecycler <Thread>::data(ii); }
136
137   /**
138    * Devuelve una cadena con la información relevante sobre este gestor de threads
139    * \return una cadena con la información relevante sobre este gestor de threads
140    */
141   std::string asString() const throw();
142
143 private:
144   const std::string a_name;
145   const Mode::_v a_mode;
146   const int a_maxSize;
147   Semaphore* a_semaphore;
148   const int a_threadFlags;
149   bool a_destroying;
150
151   // Se invoca cuando el thread detecta que va a terminar y que tiene una factoria asociada.
152   void releaseThread(Thread* thread) throw(RuntimeException);
153
154   friend class Thread;
155 };
156
157 } //namespace anna
158
159 #endif
160