YANE-Framework Tutorial 1.1.0

examples/semaphore/src/pcthread.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 "pcthread.h"
00012 
00013 #include <sstream>
00014 #include <iostream>
00015 #include <cstdlib>
00016 #include <time.h>
00017 
00018 #include <yane/utils.h>
00019 
00020 using namespace std;
00021 using namespace yane::Utils;
00022 
00023 ProduceConsumeThread::ProduceConsumeThread ( const std::string & name,
00024         yane::Utils::DebugMaster * dm, yane::Utils::Semaphore * semaphore,
00025         bool produce ) :
00026         yane::Utils::Thread ( name, dm )
00027 {
00028         _semaphore = semaphore;
00029         _produce = produce;
00030 }
00031 
00032 ProduceConsumeThread::~ProduceConsumeThread ( )
00033 {
00034 }
00035 
00036 void ProduceConsumeThread::run ( )
00037 {
00038         srand ( time ( NULL ));
00039         int tmp;
00040 
00041         // Produce thread
00042         if ( _produce )
00043         {
00044                 debugMessage ( "Produce thread started", 6 );
00045 
00046                 // Produce something
00047                 for ( int i = 0; i < 20; i++ )
00048                 {
00049                         tmp = rand ( ) % 3 + 1;
00050                         stringstream ss;
00051                         ss << tmp << " resources produced";
00052                         _semaphore->release ( tmp );
00053                         debugMessage ( ss.str ( ), 6 );
00054                         usleep ( 100000 );
00055                 }
00056 
00057                 debugMessage ( "Produce thread finished", 6 );
00058         }
00059 
00060         // Consume thread
00061         else
00062         {
00063                 debugMessage ( "Consume thread started", 6 );
00064 
00065                 while ( ! _abort )
00066                 {
00067                         _semaphore->acquire ( 10 );
00068                         debugMessage ( "10 resources acquired!", 6 );
00069                         usleep ( 10 );
00070                 }
00071 
00072                 debugMessage ( "Consume thread finished", 6 );
00073         }
00074 }