YANE-Framework Tutorial 1.1.0

examples/thread/src/threaddemo.cpp

00001 /***************************************************************************
00002  *                                                                         *
00003  * Copyright (C) 2011 by www.nonlinearmpc.com                              *
00004  *                                                                         *
00005  * Authors:                                                                *
00006  *  Juergen Pannek <juergen.pannek@googlemail.com>                         *
00007  *  Michael Schamel <michael.schamel@uni-bayreuth.de>                      *
00008  *                                                                         *
00009  ***************************************************************************/
00010 
00011 #include <iostream>
00012 #include <cstdlib>
00013 
00014 #include <yane/utils.h>
00015 
00016 #include "computationthread.h"
00017 
00018 using namespace std;
00019 using namespace yane::Utils;
00020 
00021 int main ( int argc, char *argv [ ] )
00022 {
00023         int threads = 3;
00024 
00025         ComputationThread * thread_array [ threads ];
00026 
00027         // Create DebugMaster
00028         RTClock *clock = new RTClock ( );
00029         DebugMasterConsole *dm = new DebugMasterConsole ( clock, 90 );
00030         DebugClient *debug_client = dm->newClient ( "Main" );
00031         dm->setLevel ( 6 );
00032 
00033         int sum = 0, tmp;
00034         int iter = 0;
00035         Mutex * mutex = new Mutex ( );
00036 
00037         // Create threads
00038         for ( int i = 0; i < threads; i++ )
00039         {
00040                 ostringstream oss;
00041                 oss << "Thread" << i;
00042                 thread_array [ i ] = new ComputationThread ( oss.str ( ), dm, mutex,
00043                         & sum, & iter );
00044         }
00045 
00046         debug_client->sendDebugInfo ( "Computing sum from 1 to 10" );
00047 
00048         // Start threads
00049         for ( int i = 0; i < threads; i++ )
00050         {
00051                 thread_array [ i ]->start ( );
00052         }
00053 
00054         // Wait until threads are finished
00055         for ( int i = 0; i < threads; i++ )
00056         {
00057                 thread_array [ i ]->wait ( );
00058         }
00059 
00060         // Result
00061         debug_client->sendDebugInfo ( "Threads finished.", "", 0, 0, 0, 3 );
00062         debug_client->sendDebugInfo ( "", "computed result: ", & sum, sizeof(int),
00063                 DebugMaster::T_INT );
00064 
00065         // Clean up
00066         for ( int i = 0; i < threads; i++ )
00067         {
00068                 delete thread_array [ i ];
00069         }
00070         delete mutex;
00071         delete dm;
00072         delete debug_client;
00073         delete clock;
00074 
00075         return 0;
00076 }