使用ACE_Condition

 教程中的例子演示了条件变量的使用,不过感觉这个例子的实现还是有些问题,因为在运行时可以看到,有多个线程都观察到了number==n_threads,结果都认为自己是最后一个线程,从而导致输出结果比较混乱。不过也可能是因为是在双核机器上运行才这样的,具体情况有待验证。程序代码如下:

#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

你可能感兴趣的:(thread,struct,OS,Signal)