zthread学习 实例五 非任务对象的生存期

来源:互联网 发布:tomcat端口有哪些 编辑:程序博客网 时间:2024/04/30 13:34

在使用线程处理时,必须确保非任务对象在任务需要它们的时候长期保留在活动状态,如果在任务完成之前,那些被任务使用的非任务对象已经被销毁,此时会导致非法访问存储单元。因此,那些被共享的非任务对象总要在堆中new出来,并且确保没有其他任务对象引用它时才动态销毁,此时就是引用计数。

      ZThread库有一个引用计数的模板CountedPtr<>,它自动执行引用计数(执行拷贝构造函数时),并在引用计数归0时delete这个对象。每当有对象有被多于一个任务使用时,几乎总是需要使用CountedPtr<>来管理那些对象,以防由对角生存期争端而产生的问题。


[cpp] view plaincopy
  1. #include "stdafx.h"  
  2. #include <iostream>  
  3. #include <fstream>  
  4. #include "zthread/Thread.h"  
  5. #include "zthread/Runnable.h"  
  6. #include "zthread/PoolExecutor.h"    
  7.   
  8. using namespace ZThread;  
  9. using namespace std;  
  10.   
  11. class CCount  
  12. {  
  13. public:  
  14.     void increment()  
  15.     {  
  16.         for (int i = 0; i < 100; i ++)  
  17.         {  
  18.             n[i]++;  
  19.         }  
  20.         //n++;  
  21.     }  
  22. private:  
  23.     int n[100];  
  24.     //int n;  
  25. };  
  26.   
  27. class Incrementer : public Runnable  
  28. {  
  29. public:  
  30.     //Incrementer(CCount* pC) : pCount(pC){}  
  31.     Incrementer(const CountedPtr<CCount>& pC) : pCount(pC){}  
  32.     void run()  
  33.     {  
  34.         for (int i = 100; i > 0; i--)  
  35.         {  
  36.             Thread::sleep(100);  
  37.             pCount->increment();  
  38.             cout << i << endl;  
  39.         }  
  40.     }  
  41. private:  
  42.     //CCount* pCount;  
  43.     CountedPtr<CCount> pCount;  
  44. };  
  45.   
  46.   
  47. int _tmain(int argc, _TCHAR* argv[])  
  48. {  
  49.     //CCount count;  
  50.     CountedPtr<CCount> pCount(new CCount);  
  51.     try  
  52.     {  
  53.         //Thread t0(new Incrementer(&count));  
  54.         //Thread t1(new Incrementer(&count));  
  55.   
  56.         Thread t0(new Incrementer(pCount));  
  57.         Thread t1(new Incrementer(pCount));  
  58.     }  
  59.     catch (Synchronization_Exception&  e)  
  60.     {  
  61.         cerr << e.what() <<endl;  
  62.     }  
  63.     return 0;  
  64. }  

代码中注释起来的在栈中定义的CCount对象,会出现非法访问的错误。

而由CountedPtr<>模板管理的CCount对象,在任务两次对它引用时都会增1,只要任务运行,计数就会非0,当使用CCount对象的所有任务全部完成时(此时引用计数归0),才会delete  CCount对象。

0 0
原创粉丝点击