Listing 6: Test driver for use with sample object in Listing 5

// File : test.cpp"

#include <windows.h>
#include <process.h>
#include <conio.h>
#include <iostream>

using namespace std;

#include "CMonitor.h"  
#include "Foo.h"

typedef CMonitor<Foo>      FooMonitor;

void MonitorThreadFunction1( void* pVoid )  // uses monitor
{
   FooMonitor*     pMonitor = (FooMonitor*)pVoid;

   try 
   {
      for( int i = 0; i < 100; i++ )
      {
         pMonitor->Safe().element().inc(10);
         Sleep( 100 );
      }
   }

   catch(MutexException e)
   {
      if( e == TIMEOUT )
      {
         cout << "Timeout on wait !" << endl;
      }
   }
}

void MonitorThreadFunction2( void* pVoid )  // uses monitor
{
   FooMonitor* pMonitor = (FooMonitor*)pVoid;

   try 
   {
      for( int i = 0; i < 100; i++ )
      {
         cout << "The value is : "
              << pMonitor->Safe().element().value() << endl;
         Sleep( 100 );
      }
   }

   catch(MutexException e)
   {
      if( e == TIMEOUT )
      {
         cout << "Timeout on wait !" << endl;
      }
   }
}

void ThreadFunction1( void* pVoid )    // no monitor
{
   Foo* pFoo = (Foo*)pVoid;

   for( int i = 0; i < 100; i++ )
   {
      pFoo->inc(10);
      Sleep( 100 );
   }
}

void ThreadFunction2( void* pVoid )   // no monitor
{
   Foo* pFoo = (Foo*)pVoid;

   for( int i = 0; i < 100; i++ )
   {
      cout << "The value is : " << pFoo->value() << endl;
      Sleep( 100 );
   }
}

int main( int argc, char** argv )
{
   Foo               foo;
   FooMonitor        monitor(foo);


   if( (argc == 1) || (argv[1][0] != 'M' && argv[1][0] != 'm') )
   {
      _beginthread( ThreadFunction1, 0, (void*)&foo);
      _beginthread( ThreadFunction2, 0, (void*)&foo);
   }
   else
   {
      _beginthread( MonitorThreadFunction1, 0, (void*)&monitor);
      _beginthread( MonitorThreadFunction2, 0, (void*)&monitor);
   }

   _getch();

   return 0;
}
//End of File