Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1063278
  • 博文数量: 284
  • 博客积分: 8223
  • 博客等级: 中将
  • 技术积分: 3188
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-01 13:26
文章分类

全部博文(284)

文章存档

2012年(18)

2011年(33)

2010年(83)

2009年(147)

2008年(3)

分类: C/C++

2009-08-03 19:47:02

#include "stdafx.h"
#include
#include
#include
#include
const int Max = 20;
boost::mutex mutex;
boost::condition cond;
class product
{
public:
 product()
 :count(0)
 {}
 void make();
 void take();
 int num();
private:
 int count;
};
void product::make()
{
 count++;
}
void product::take()
{
 if(count>0) count--;
}
int product::num()
{
 return count;
}
product pro;
void c()
{
 {
  boost::mutex::scoped_lock lock(mutex);
  while(pro.num() }
 for(;;){
  boost::mutex::scoped_lock lock(mutex);
  if(pro.num()>0) {
   pro.take();
   std::cout<<"decrease: "<< pro.num()<<"\n";
  }else  {
   std::cout<<"decrease end\n"<< "\n";
   break;
  }
 }
}
void p()
{
 for(;;){
  boost::mutex::scoped_lock lock(mutex);
  pro.make();
  std::cout<<"increase: "<< pro.num()<< "\n";
  if(pro.num()>Max) {
   std::cout<<"increase end\n"<< "\n";
   cond.notify_all();
   break;
  }
 }
}
 
int _tmain(int argc, _TCHAR* argv[])
{
    boost::thread thrd1(&p);
    boost::thread thrd2(&p);
    boost::thread thrd3(&c);
    thrd1.join();
    thrd2.join();
    thrd3.join();
 return 0;
}
阅读(761) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~