ACE:条件类属(Condition)

考虑场景:设想线程需要在全局消息队列里插入消息,首先它要判断是否还有空闲,如果没有,要继续等待直到其他线程释放了该空间。

使用条件变量要注意以下步骤

1.获取全局资源(消息队列)锁。

2.检查条件(消息队列有空闲吗?)

3.如果没有wait().(注:条件变量的wait()会释放1中的锁,以使其他线程能获取全局资源。一旦收到signal()信号,会继续获得锁,并检查条件2。)

4.如果条件为真,则在全局资源上进行操作。


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




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




class Args{
public:
Args(ACE_Condition<ACE_Thread_Mutex> *cond,int nThreads):_pCond(cond),
nThreads(nThreads),_mutex()
{
}
ACE_Condition<ACE_Thread_Mutex> *_pCond;
ACE_Thread_Mutex _mutex;
int nThreads;
};


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


ACE_DEBUG((LM_DEBUG,"【%t】created to do some work\n"));




ACE_OS::sleep(ACE_OS::rand()%2);

args->_mutex.acquire(); 
::number++;
ACE_DEBUG((LM_DEBUG,"【%t】thread is done\n"));
args->_mutex.release();



if(args->nThreads==number)
{
ACE_DEBUG((LM_DEBUG,"【%t】All threads complete\n"));
args->_pCond->signal();
}


return 0;
}




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



thread_num = 5;

ACE_OS::srand(::seed);

ACE_Thread_Mutex mutex;
ACE_Condition<ACE_Thread_Mutex> cond(mutex);
Args arg(&cond,thread_num);

for(int i=0;i<thread_num;i++)
{
if(ACE_Thread::spawn((ACE_THR_FUNC)worker,(void*)&arg,
THR_DETACHED|THR_NEW_LWP)==-1)

ACE_DEBUG((LM_DEBUG,"Error spawn threads\n"));
}

mutex.acquire();
while(::number!=thread_num)
cond.wait();

ACE_DEBUG((LM_DEBUG,"【%t】 Main thread end\n"));

mutex.release();
ACE_OS::exit(0);

return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

self-motivation

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值