1 // ANNA - Anna is Not Nothingness Anymore //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo //
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 //
11 #include <anna/core/mt/ThreadManager.hpp>
12 #include <anna/core/util/CommandLine.hpp>
13 #include <anna/core/mt/Mutex.hpp>
14 #include <anna/core/tracing/Logger.hpp>
15 #include <anna/core/mt/Runnable.hpp>
16 #include <anna/core/mt/Thread.hpp>
17 #include <anna/core/tracing/TraceWriter.hpp>
22 class MyRunnable : public Runnable {
24 MyRunnable () : Runnable () {;}
27 void initialize () throw (RuntimeException);
28 void run () throw (RuntimeException);
29 void terminate () throw ();
31 anna_complete_runnable (MyRunnable);
34 int main (const int argc, const char** argv)
36 CommandLine& ccll = CommandLine::instantiate ();
37 ThreadManager* threadManager (NULL);
40 ccll.add ("maxthr", CommandLine::Argument::Mandatory, "Maximum number of threads");
41 ccll.add ("mode", CommandLine::Argument::Mandatory, "Manager instance mode");
42 ccll.add ("nthr", CommandLine::Argument::Mandatory, "Number of threads to create");
44 ccll.initialize (argv, argc);
47 Logger::initialize ("thread_manager", new TraceWriter ("file.trace", 2048000));
49 ThreadManager::Mode::_v mode = ThreadManager::Mode::asEnumEx (ccll.getValue ("mode"));
51 const int maxThread = ccll.getIntegerValue ("maxthr");
52 int nthr = max (2, ccll.getIntegerValue ("nthr"));
54 threadManager = new ThreadManager ("MyManager", mode, maxThread, Thread::Flag::Joinable);
55 MyRunnable* myRunnable;
58 // Se genrean memory-leaks en los MyRunnable, pero no nos interesa complicar el ejemplo
59 for (int ii = 0; ii < nthr; ii ++) {
60 myRunnable = new MyRunnable ();
61 thread = threadManager->createThread ();
62 thread->start (*myRunnable);
65 // Espera la terminaciĆ³n de todos los threads asociados al gestor que siguen corriendo
66 threadManager->join ();
68 // Crea un thread y espera su terminaciĆ³n
69 Thread* aux = threadManager->createThread ();
70 myRunnable = new MyRunnable ();
71 aux->start (*myRunnable);
74 catch (RuntimeException& ex) {
75 cout << ex.asString () << endl << endl;
80 void MyRunnable::initialize ()
81 throw (RuntimeException)
84 string msg (asString ());
85 msg += " | initialize ...";
86 Logger::debug (msg, ANNA_FILE_LOCATION);
90 void MyRunnable::run ()
91 throw (RuntimeException)
93 const int delay = rand () % 2000;
96 string msg (asString ());
97 msg += functions::asText (" | Waiting: ", delay);
99 Logger::debug (msg, ANNA_FILE_LOCATION);
102 anna::functions::sleep ((Millisecond)delay);
105 void MyRunnable::terminate ()
109 string msg (asString ());
110 msg += " | terminate ... ";
111 Logger::debug (msg, ANNA_FILE_LOCATION);