使用ACE_Condition

本文探讨了一个并发编程实例中条件变量使用的错误实现,指出多个线程可能同时认为自己是最后一个线程的问题,并提供了可能的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 教程中的例子演示了条件变量的使用,不过感觉这个例子的实现还是有些问题,因为在运行时可以看到,有多个线程都观察到了number==n_threads,结果都认为自己是最后一个线程,从而导致输出结果比较混乱。不过也可能是因为是在双核机器上运行才这样的,具体情况有待验证。程序代码如下:

#include<ace/Synch.h>
#include<ace/Thread.h>

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

struct 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"));
 number++;
 ACE_OS::sleep(2);
 ACE_DEBUG((LM_DEBUG,"\tThread (%t) done!\n\tThe number is now: %d\n",number));
 if(number==arg->threads_)
 {
  ACE_DEBUG((LM_DEBUG,"(%t) Last thread!\nAll threads have done their job! Signal main thread\n"));
  arg->cond_->signal();
 }
 return 0;
}

int main(int argc,char* argv[])
{
 if(argc<2)
 {
  ACE_OS::printf("Usage: %s <number_of_threads>\n",argv[0]);
  ACE_OS::exit(1);
 }
 int n_threads=ACE_OS::atoi(argv[1]);
 ACE_OS::srand(::seed);
 ACE_Thread_Mutex mutex;
 ACE_Condition<ACE_Thread_Mutex> cond(mutex);
 Args arg(&cond,n_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"));
 }
 mutex.acquire();
 while(number!=n_threads)
  cond.wait();
 ACE_DEBUG((LM_DEBUG,"(%t) Main thread got signal. Program is exiting...\n"));
 mutex.release();
 return 0;
}

一次运行结果如下:

Thread (9792) created to do some work
Thread (8940) created to do some work
Thread (9112) created to do some work
        Thread (8940) done!
        The number is now: 3
(8940) Last thread!
All threads have done their job! Signal main thread
        Thread (9792) done!
        The number is now: 3
        Thread (9112) done!
        The number is now: 3
(4880) Main thread got signal. Program is exiting...
(9792) Last thread!
All threads have done their job! Signal main thread
(9112) Last thread!
All threads have done their job! Signal main thread

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值