zthread学习 实例六 访问控制

就是对共享资源的同步访问,以免造成不确定的状态。

Zhread库是基于Mutex临界区来组建同步机制的。


[cpp]  view plain copy
  1. #include "stdafx.h"  
  2. #include <iostream>  
  3. #include <fstream>  
  4.   
  5. #include "zthread/Guard.h"  
  6. #include "zthread/Mutex.h"  
  7. #include "zthread/ThreadedExecutor.h"  
  8. #include "zthread/Cancelable.h"  
  9. #include "zthread/Runnable.h"  
  10. #include "zthread/Thread.h"  
  11.   
  12. using namespace ZThread;  
  13. using namespace std;  
  14.   
  15. //用于共享资源的虚基类,  
  16. class Generator : public Cancelable  
  17. {  
  18. public:  
  19.     Generator(): canceled(false){}  
  20.     virtual int nextValue() = 0;  
  21.     void cancel() {canceled = true;}  
  22.     bool isCanceled(){return canceled;}  
  23. private:  
  24.     bool canceled;  
  25. };  
  26.   
  27. //实现基类的虚函数nextValue()  
  28. class EvenGenerator : public Generator  
  29. {  
  30. public:  
  31.     EvenGenerator()  
  32.     {  
  33.         currentEvenValue = 0;  
  34.     }  
  35.     ~EvenGenerator()  
  36.     {  
  37.         cout << "~EvenGenerator" << endl;  
  38.     }  
  39.     int nextValue()  
  40.     {  
  41.         Guard<Mutex> g(Lock);     //同步控制  
  42.         currentEvenValue++;  
  43.         Thread::yield();        //放大因线程调度问题产生的不一致  
  44.         currentEvenValue++;  
  45.         return currentEvenValue;  
  46.     }  
  47. private:  
  48.     unsigned int currentEvenValue;  
  49.     Mutex   Lock;  
  50. };  
  51.   
  52.   
  53. //任务类,重点run()函数  
  54. class EvenChecker : public Runnable  
  55. {  
  56. public:  
  57.     EvenChecker(const CountedPtr<Generator>& g, int idn): pGenerator(g), id(idn){}  
  58.     ~EvenChecker()  
  59.     {  
  60.         cout << "~EvenChecker" << id <<endl;  
  61.     }  
  62.     void run()  
  63.     {  
  64.         while (!pGenerator->isCanceled())                //检查任务共享资源是否已退出,通过控制共享资源来控制所有创建的任务是否需要返回  
  65.         {  
  66.             int val = pGenerator->nextValue();  
  67.             if (val % 2 != 0)  
  68.             {  
  69.                 cout << val << " not even!" <<endl;  
  70.                 pGenerator->cancel();                    //共享资源退出  
  71.             }  
  72.             else  
  73.             {  
  74.                 cout <<"ID: "<<id << ", value = " << val<<endl;  
  75.                 Thread::sleep(200);  
  76.             }  
  77.         }  
  78.     }  
  79.     template<typename GenType>   
  80.     static void test(int n = 5)  
  81.     {  
  82.         try  
  83.         {  
  84.             ThreadedExecutor executor;  
  85.             CountedPtr<Generator> pGp(new GenType);  
  86.             for (int i = 0; i < n; i++)  
  87.             {  
  88.                 executor.execute(new EvenChecker(pGp, i));          //引用同一个Generator,多个任务共享  
  89.             }  
  90.         }  
  91.         catch (Synchronization_Exception& e)  
  92.         {  
  93.             cerr << e.what() << endl;  
  94.         }  
  95.     }  
  96. private:  
  97.     CountedPtr<Generator> pGenerator;  
  98.     int id;  
  99. };  
  100.   
  101. int _tmain(int argc, _TCHAR* argv[])  
  102. {  
  103.     try  
  104.     {  
  105.         EvenChecker::test<EvenGenerator>();  
  106.     }  
  107.     catch (Synchronization_Exception&  e)  
  108.     {  
  109.         cerr << e.what() <<endl;  
  110.     }  
  111.     cin.get();  
  112.     return 0;  
  113. }  

Guard<>模板很方便的定义了同步机制,它在创建时用acquire()来获得一个Lockable对象,被销毁时用release()来释放这个锁。Guard对象的创建很好的利用了变量作用域概念。例如:

 

void fun()

{

      ... ...

      {    //特意添加的用于控制Guard作用域的括号

            Guard<Mutex> g(Lock);

            ... ...//重点临界区代码

       }

}

 

Zhread库中给Guard<>提供了4种类型的锁策略:

1、CompoundScope

     Note: Locking policy that aggregates two policies that share a target.It is not appropriate to use with any type of OverlappedScope

 

2、LockedScope(默认)

     Note: Locking policy for Lockable objects. This policy acquire()s a Lockable when the protection scope is created, and it release()s a Lockable when the scope is destroyed.

 

3、UnlockedScope(解锁)

     Note: Locking policy for Lockable objects. This policy release()s a Lockable when the protection scope is created, and it acquire()s a Lockable when the scope is destroyed.

4、TimedLockedScope(带时间)

      Note:  Locking policy that attempts to enterScope some resource in a certain amount of time using an tryEnterScope-relase protocol.

 

5、OverlappedScope

    Note:  Locking policy allows the effective scope of two locks to overlap by releasing and disabling one lock before its Guard does so.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值