ACE:使用令牌作为递归互斥锁

令牌的特性:

它可以被最初获得它的线程进行多次的重新获取,而且确保所有试图获得它的线程严格按照先进先出的顺序排序。运行下面程序,观察不同线程请求令牌与获得令牌的顺序。


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


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


struct Args{


public:
Args(int iterations):_token("My token"),
iterations(iterations){}
ACE_Token _token;
int iterations;
};


static void* worker(void* arguments)
{
struct 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"));
args->_token.acquire();
ACE_DEBUG((LM_DEBUG,"(%t) get the hold of iterations [%d]\n",i));
ACE_OS::sleep(2);
args->_token.release();
}

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]);
struct Args args(thread_num);

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;
}

  • 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、付费专栏及课程。

余额充值