ACE中的ACE_Thread_Mutex 类

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

struct Args
{
public:
    Args(int iterations) : mutex_(), iterations_(iterations) {}
    ACE_Thread_Mutex mutex_;
    int iterations_;
};

static void* worker(void* arguments)
{
    Args* arg = (Args*)arguments;
    for (int i = 0; i < arg->iterations_; i++)
    {
        ACE_DEBUG((LM_DEBUG, "(%t) Trying to get a hold of this iteration\n"));

        //This is our critical section 
        arg->mutex_.acquire();
        ACE_DEBUG((LM_DEBUG, "(%t) This is iteration number %d\n", i));
        ACE_OS::sleep(2);

        //simulate critical work 
        arg->mutex_.release();
    }

    return 0;
}

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        ACE_OS::printf("Usage: %s <number_of_threads> < number_of_iterations > \n", argv[0]); 
        ACE_OS::exit(1);
    }
    Args arg(ACE_OS::atoi(argv[2]));

    //Setup the arguments 
    int n_threads = ACE_OS::atoi(argv[1]);


    //determine the number of threads to be spawned. 
    ACE_thread_t* threadID = new ACE_thread_t[n_threads + 1];
    ACE_hthread_t* threadHandles = new ACE_hthread_t[n_threads + 1];
    if (ACE_Thread::spawn_n(threadID, //id’s for each of the threads 
        n_threads, //number of threads to spawn 
        (ACE_THR_FUNC)worker, //entry point for new thread 
        &arg, //args to worker 
        THR_JOINABLE | THR_NEW_LWP, //flags 
        ACE_DEFAULT_THREAD_PRIORITY,
        0, 0, threadHandles) == -1)
        ACE_DEBUG((LM_DEBUG, "Error in spawning thread\n"));

    //spawn n_threads 
    for (int i = 0; i < n_threads; i++)
        ACE_Thread::join(threadHandles[i]);

    //Wait for all the threads to exit before you let the main fall through 
   //and have the process exit. 
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值