zhtread c++多线程库的使用5: 线程的本地化存储

消除线程在共享资源上的冲突的一个办法是消除共享的资源变量 ,因而就可以对同一对象的不同线程分配不同的存储单元

 

这是由threadloca模板来实现的

 

如下所示

#include #include "zthread/Thread.h" #include "zthread/Mutex.h" #include "zthread/Guard.h" #include "zthread/ThreadedExecutor.h" #include "zthread/Cancelable.h" #include "zthread/ThreadLocal.h" #include "zthread/CountedPtr.h" #include using namespace ZThread; using namespace std; #pragma comment(lib,"ZThread_D.lib") //线程的本地化存储变量 class ThreadLocalVariables : public Cancelable { //本地化存储的模板 ThreadLocal value; bool canceled; //?? Mutex lock; public: ThreadLocalVariables() : canceled(false) { value.set(0); } void increment() { value.set(value.get() + 1); } int get() { return value.get(); } void cancel() { Guard g(lock); canceled = true; } bool isCanceled() { Guard g(lock); return canceled; } }; class Accessor : public Runnable { int id; //引用计数指针 CountedPtr tlv; public: Accessor(CountedPtr& tl, int idn) : id(idn), tlv(tl) {} //重载run方法 void run() { while(!tlv->isCanceled()) { tlv->increment(); cout << *this << endl; _sleep(20); } } friend ostream& operator<<(ostream& os, Accessor& a) { return os << "#" << a.id << ": " << a.tlv->get(); } }; int main() { cout << "Press to quit" << endl; try { CountedPtr tlv(new ThreadLocalVariables); const int SZ = 2; ThreadedExecutor executor; for(int i = 0; i < SZ; i++) executor.execute(new Accessor(tlv, i)); cin.get(); tlv->cancel(); // All Accessors will quit } catch(Synchronization_Exception& e) { cerr << e.what() << endl; } _sleep(1234); } ///:~

 

代码先放这里 虽然一下子没看懂

你可能感兴趣的:(zthread,c++)