#include<ace/Synch.h>
#include<ace/Thread.h>
static int number=0;
static int seed=0;
struct Args
{
public:
Args(ACE_Condition<ACE_Thread_Mutex>* cond,int threads):cond_(cond),threads_(threads){}
ACE_Condition<ACE_Thread_Mutex>* cond_;
int threads_;
};
static void* worker(void* arguments)
{
Args* arg=(Args*)arguments;
ACE_DEBUG((LM_DEBUG,"Thread (%t) created to do some work\n"));
number++;
ACE_OS::sleep(2);
ACE_DEBUG((LM_DEBUG,"\tThread (%t) done!\n\tThe number is now: %d\n",number));
if(number==arg->threads_)
{
ACE_DEBUG((LM_DEBUG,"(%t) Last thread!\nAll threads have done their job! Signal main thread\n"));
arg->cond_->signal();
}
return 0;
}
int main(int argc,char* argv[])
{
if(argc<2)
{
ACE_OS::printf("Usage: %s <number_of_threads>\n",argv[0]);
ACE_OS::exit(1);
}
int n_threads=ACE_OS::atoi(argv[1]);
ACE_OS::srand(::seed);
ACE_Thread_Mutex mutex;
ACE_Condition<ACE_Thread_Mutex> cond(mutex);
Args arg(&cond,n_threads);
for(int i=0;i<n_threads;i++)
{
if(ACE_Thread::spawn((ACE_THR_FUNC)worker,(void*)&arg,THR_DETACHED|THR_NEW_LWP)==-1)
ACE_DEBUG((LM_DEBUG,"Error in spawning thread\n"));
}
mutex.acquire();
while(number!=n_threads)
cond.wait();
ACE_DEBUG((LM_DEBUG,"(%t) Main thread got signal. Program is exiting...\n"));
mutex.release();
return 0;
}
一次运行结果如下:
Thread (9792) created to do some work
Thread (8940) created to do some work
Thread (9112) created to do some work
Thread (8940) done!
The number is now: 3
(8940) Last thread!
All threads have done their job! Signal main thread
Thread (9792) done!
The number is now: 3
Thread (9112) done!
The number is now: 3
(4880) Main thread got signal. Program is exiting...
(9792) Last thread!
All threads have done their job! Signal main thread
(9112) Last thread!
All threads have done their job! Signal main thread