/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//// This example is from the ACE Programmers Guide.
//// Chapter: "Thread Management"
//// For details please see the guide at
//// http://www.cs.wustl.edu/~schmidt/ACE.html
//// AUTHOR: Umar Syyid (usyyid@hns.com)
//// and Ambreen Ilyas (ambreen@bitsmart.com)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Example 3
#include "ace/OS.h"
#include "ace/Synch.h"
#include "ace/Synch_T.h"

//Arguments that are to be passed to the worker thread are passed through this class.
class Args{
public:
Args(ACE_Lock* lock,int iterations):
mutex_(lock),iterations_(iterations){}
ACE_Lock* mutex_;
int iterations_;
};

//The starting point for the worker threads
static void*
worker(void*arguments){
Args *arg= (Args*) arguments;
for(int i=0;i<arg->iterations_;i++){
ACE_DEBUG((LM_DEBUG,
"(%t) Trying to get a hold of this iteration\n"));
//This is our critical section
arg->mutex_->acquire();
ACE_DEBUG((LM_DEBUG,"(%t) This is iteration number %d\n",i));
//work
ACE_OS::sleep(2);
arg->mutex_->release();
}
return 0;
}

int main(int argc, char*argv[]){
if(argc<4){
ACE_OS::printf("Usage: egx <number_of_threads>
<number_of_iterations> <lock_type>\n");
ACE_OS::exit(1);
}
//Lock used by application
ACE_Lock *lock;

//Decide which lock you want to use at run time. Possible due to
//ACE_Lock.
if(ACE_OS::strcmp(argv[3],"Thread"))
lock=new ACE_Lock_Adapter<ACE_Thread_Mutex>;
else
lock=new ACE_Lock_Adapter<ACE_Mutex>

//Setup the arguments
Args arg(lock,ACE_OS::atoi(argv[2]));
//Spawn the worker threads
ACE_Thread::spawn_n
(ACE_OS::atoi(argv[1]),(ACE_THR_FUNC)worker,(void*)&arg);
while(ACE_Thread::join(NULL,NULL,NULL)==0);
}

Next Example