ACE_Condition使用

14 篇文章 1 订阅

       不知道ACE怎么才能学好,感觉好复杂好抽象,,也不懂设计模式。。

       ACE_Condition是针对OS条件变量原语的包装类。条件变量不是被用作互斥原语,而是用作特定条件已经满足的指示器。

       ACE_Condition<ACE_Thread_Mutex> cond(ACE_Thread_Mutex);

       需要特别注意的是,在阻塞在wait调用中之前,条件变量机制(ACE_Cond)负责释放全局资源的互斥体(使用ACE_Thread::join()调用可以使主线程等待其他的线程结束,条件变量也可以实现)。

       条件变量不是用于互斥,而是用于我们所描述的发送信号功能。(除了ACE_Condition类,ACE还包括ACE_Condition_Thread_Mutex类,它使用ACE_Thread_Mutex作为全局资源的底层锁定机制),比如将下面work线程中的锁(acquire,release)机制去掉,就会打印出多个线程都认为自己是最后一个线程。如果信号signal去掉,wait就会一直阻塞下去。网上部分人理解是错的,ACE明确指出条件变量不是用于互斥。


#include "ace/Thread.h"
#include "ace/Synch.h"
#include <QtCore/QCoreApplication>

static int number = 0;
static int seed = 0;

class 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"));
	arg->cond_->mutex().acquire();
	::number++;
	//work
	ACE_OS::sleep(ACE_OS::rand() % 2);
	//exiting now
	ACE_DEBUG((LM_DEBUG,"Thread (%t) Done ! The Number is now: %d\n",number));
	//if all threads are done signal main thread that program can now exit
	if(number == arg->threads_)
	{
		ACE_DEBUG((LM_DEBUG,"Last Thread ! All threads have done their job. Signal main thread.\n"));
		arg->cond_->signal();
	}
	arg->cond_->mutex().release();
	return 0;
}

int main(int argc, char *argv[])
{
	int n_threads = 4;

	//Setup the random number generator
	ACE_OS::srand(::seed);

	//setup arguments for threads
	ACE_Thread_Mutex mutex;
	ACE_Condition<ACE_Thread_Mutex> cond(mutex);
	Args arg(&cond,n_threads);

	//spawn off n_threads number of 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"));
		}
	}

	//wait for signal indicating that all threads are done and program
	//can exit. the global resource here is "number" and the condition
	//that the condition variable is waiting for is number == n_threads.
	mutex.acquire();

	while(number != n_threads)
	{
		cond.wait();
	}

	mutex.release();
	
	ACE_DEBUG((LM_DEBUG,"(%t) Main thread got signal. Program exiting...\n"));

	ACE_OS::exit(0);

	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值