ZThread的访问共同资源

使用ZThread访问同一资源,使用互斥加锁和挂起线程,这样对搜索引擎的无限爬取又进了一步。

------------------------------------------

#include "stdafx.h"
#include "zthread/Thread.h"
#include "zthread/Condition.h"
#include "zthread/Mutex.h"
#include "zthread/Guard.h"
#include "zthread/ThreadedExecutor.h"
#include "zthread/Runnable.h"
#include "zthread/CountedPtr.h"

#include <deque>
#include <string>
#include <fstream>

using namespace std;
using namespace ZThread;

ifstream in("string.txt");

static const int cntMaxSize = 5;   //放进deque的最大链接数 比如:10000

static const int cntWakeUp = 3;    //中间一个状态的唤醒 比如:6000

deque<string> ds;

class CInput:public Runnable
{
private:
 Mutex lock;
 Condition cond;
 bool bInputReady;

public:
 CInput():cond(lock)
 {
  bInputReady = false;

  cout<<"t1 join!/n";
 }

 void InputReady()
 {
  Guard<Mutex> g(lock);
  bInputReady = true;
  cond.signal();
 }

 void run()
 {
  
  while(!Thread::interrupted()) 
  {
   
   Guard<Mutex> g(lock);
  
   while(!bInputReady)
   {
    cond.wait();
   }
   
   string s;

   while(getline(in,s))
   {   
    ds.push_back(s);    
    cout<<"Push string /n";

    while(ds.size()==cntMaxSize)
    {
     cond.wait();
    }

   }
     

   bInputReady = false;
  }

  

 }

};

class COutput:public Runnable
{
private:
 Mutex lock;
 Condition cond;
 bool bOutputReady;
 
public:
 COutput():cond(lock)
 {
  bOutputReady = false;
  cout<<"t2 join!/n";
 }
 ~COutput(){} 

 void OutputReady()
 {
  Guard<Mutex> g(lock);
  bOutputReady = true;
  cond.signal();
 }

 void run()
 {
  while(!Thread::interrupted())
  { 
   Guard<Mutex> g(lock);

   while(!bOutputReady)
   {
    cond.wait();
   }

   string str = ds.front();
   ds.pop_front();

   cout<<str<<endl;

   bOutputReady = false;
  }
 

 }
};

class CRun:public Runnable
{
private:
 Mutex lock;
public:
 void run()
 {
  
  CInput* input = new CInput;
  COutput* output = new COutput;
  
  ThreadedExecutor exe;
  exe.execute(input);
  exe.execute(output);

  while(!Thread::interrupted())
  {
   Guard<Mutex> g(lock);
     
   if(ds.empty()||ds.size()==cntWakeUp)
   {    
    input->InputReady();
   }

   if(!ds.empty())
   {
    output->OutputReady();
   }
  

  }

  exe.interrupt();
 
 }
};

void main(void)
{
 Thread t(new CRun);

 cin.get();

 t.interrupt();
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值