zthread学习 实例七 线程本地存储

消除任务在共享资源上发生冲突问题的第二种方法是 消除共享变量,对使用同一个变量的不同线程,可以为同一个变量创建不同的存储单元。因此,如果有5个线程使用一个含有变量x的对象,线程本地存储会自动为变量产生5个不同的存储单元。


[cpp]  view plain copy
  1. #include "stdafx.h"  
  2. #include <iostream>  
  3. #include <fstream>  
  4.   
  5. #include "zthread/ThreadLocal.h"  
  6. #include "zthread/Guard.h"  
  7. #include "zthread/Mutex.h"  
  8. #include "zthread/ThreadedExecutor.h"  
  9. #include "zthread/Cancelable.h"  
  10. #include "zthread/Runnable.h"  
  11. #include "zthread/Thread.h"  
  12.   
  13.   
  14. using namespace ZThread;  
  15. using namespace std;  
  16.   
  17. class ThreadVariables : public Cancelable  
  18. {  
  19. public:  
  20.     ThreadVariables(): canceled(false)  
  21.     {  
  22.         Value.set(0);  
  23.     }  
  24.     void increament() {Value.set(Value.get() + 1);}  
  25.     int get() {return Value.get();}  
  26.   
  27.     void cancel()  
  28.     {  
  29.         Guard<Mutex> g(Lock);  
  30.         canceled = true;  
  31.     }  
  32.     bool isCanceled()  
  33.     {  
  34.         Guard<Mutex> g(Lock);  
  35.         return canceled;  
  36.     }  
  37. private:  
  38.     ThreadLocal<int> Value;  
  39.     bool canceled;  
  40.     Mutex  Lock;  
  41. };  
  42.   
  43. class Accessor : public Runnable  
  44. {  
  45. public:  
  46.     Accessor(const   
  47.         CountedPtr<ThreadVariables>&  tl, int idn = 0):  
  48.     id(idn), pTlv(tl) {}  
  49.     void run()  
  50.     {  
  51.         while (!pTlv->isCanceled())  
  52.         {  
  53.             pTlv->increament();  
  54.             cout<<*this<<endl;  
  55.         }  
  56.     }  
  57.     friend ostream& operator <<(ostream& os, Accessor& a)  
  58.     {  
  59.         Thread::sleep(200);  
  60.         return os << " # " << a.id << " : " << a.pTlv->get()<<endl;  
  61.     }  
  62. private:  
  63.     int id;  
  64.     CountedPtr<ThreadVariables> pTlv;  
  65. };  
  66.   
  67. int _tmain(int argc, _TCHAR* argv[])  
  68. {  
  69.     try  
  70.     {  
  71.         CountedPtr<ThreadVariables> tlv(new ThreadVariables);  
  72.   
  73.         ThreadedExecutor executor;  
  74.         for (int i = 0; i < 5; i++)  
  75.         {  
  76.             executor.execute(new Accessor(tlv, i));  
  77.         }  
  78.         cin.get();  
  79.         tlv->cancel();  
  80.     }  
  81.     catch (Synchronization_Exception&  e)  
  82.     {  
  83.         cerr << e.what() <<endl;  
  84.     }  
  85.     cin.get();  
  86.     return 0;  
  87. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值