ACE:守卫类属

ACE_Guard是一种模版,它通过所需的锁机制来定制类型。工作原理是:构造函数里获取锁,析构函数里释放锁。

所以下面的代码会看到,一旦某个线程获得了锁,那么这个线程会执行完毕,其他线程才能再获得锁。


#include <stdio.h>
#include <stdlib.h>


#include "ace/Token.h"
#include "ace/Synch.h"
#include "ace/Thread.h"
#include "ace/Log_Msg.h"


class Args{
public:
Args(int iterations):_mutex(),
iterations(iterations){}
ACE_Thread_Mutex _mutex;
int iterations;
};


static void* worker(void* arguments)
{
  Args *args = (Args *)arguments;

for(int i = 0;i<args->iterations;i++)
{
ACE_DEBUG((LM_DEBUG,"(%t) Tring to get a hold of this iterations\n"));
ACE_Guard<ACE_Thread_Mutex> guard(args->_mutex);
{
ACE_DEBUG((LM_DEBUG,"(%t) get the hold of iterations [%d]\n",i));
ACE_OS::sleep(2);
}
}

ACE_DEBUG((LM_DEBUG,"(%t) EXIT\n"));
return 0;

}


int main(int argc,char* argv[])
{
int thread_num = 0;

if(argc<3)
{
ACE_OS::printf("Usage:%s <number of threads>\
<number of iterations>\n",argv[0]);

ACE_OS::exit(1);

}


thread_num = ACE_OS::atoi(argv[1]);
Args args(ACE_OS::atoi(argv[2]));

ACE_thread_t *thread_id = new ACE_thread_t[thread_num+1];
ACE_hthread_t *thread_handles = new ACE_hthread_t[thread_num+1];

if(ACE_Thread::spawn_n(thread_id,thread_num,(ACE_THR_FUNC)worker,
&args,THR_JOINABLE|THR_NEW_LWP,ACE_DEFAULT_THREAD_PRIORITY,
0,0,thread_handles)==-1)
{
ACE_DEBUG((LM_DEBUG,"Error in spawn threads\n"));
}

for(int i=0;i<thread_num;i++)
{
ACE_Thread::join(thread_handles[i]);
}

return 0;
}

你可能感兴趣的:(JOIN,thread,工作,OS)