消除任务在共享资源上发生冲突问题的第二种方法是 消除共享变量,对使用同一个变量的不同线程,可以为同一个变量创建不同的存储单元。因此,如果有5个线程使用一个含有变量x的对象,线程本地存储会自动为变量产生5个不同的存储单元。
- #include "stdafx.h"
- #include <iostream>
- #include <fstream>
- #include "zthread/ThreadLocal.h"
- #include "zthread/Guard.h"
- #include "zthread/Mutex.h"
- #include "zthread/ThreadedExecutor.h"
- #include "zthread/Cancelable.h"
- #include "zthread/Runnable.h"
- #include "zthread/Thread.h"
- using namespace ZThread;
- using namespace std;
- class ThreadVariables : public Cancelable
- {
- public:
- ThreadVariables(): canceled(false)
- {
- Value.set(0);
- }
- void increament() {Value.set(Value.get() + 1);}
- int get() {return Value.get();}
- void cancel()
- {
- Guard<Mutex> g(Lock);
- canceled = true;
- }
- bool isCanceled()
- {
- Guard<Mutex> g(Lock);
- return canceled;
- }
- private:
- ThreadLocal<int> Value;
- bool canceled;
- Mutex Lock;
- };
- class Accessor : public Runnable
- {
- public:
- Accessor(const
- CountedPtr<ThreadVariables>& tl, int idn = 0):
- id(idn), pTlv(tl) {}
- void run()
- {
- while (!pTlv->isCanceled())
- {
- pTlv->increament();
- cout<<*this<<endl;
- }
- }
- friend ostream& operator <<(ostream& os, Accessor& a)
- {
- Thread::sleep(200);
- return os << " # " << a.id << " : " << a.pTlv->get()<<endl;
- }
- private:
- int id;
- CountedPtr<ThreadVariables> pTlv;
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- try
- {
- CountedPtr<ThreadVariables> tlv(new ThreadVariables);
- ThreadedExecutor executor;
- for (int i = 0; i < 5; i++)
- {
- executor.execute(new Accessor(tlv, i));
- }
- cin.get();
- tlv->cancel();
- }
- catch (Synchronization_Exception& e)
- {
- cerr << e.what() <<endl;
- }
- cin.get();
- return 0;
- }