使STL容器线程安全的类(转载)

// ThreadSafeObject.h 
//  ThreadSafeObject by David Maisonave (609-345-1007) (www.axter.com)
/*
Description:ThreadSafeObject is a thread safe wrapper class, 
which uses windows API Critical-Section logic. 
It can turn any object into a thread safe object.
ThreadSafeObject destructor will automatically destroy the object,
so the object can be create via new on ThreadSafeObject constructor.
This insures no other process has ownership of the object.
Example Usage
ThreadSafeObject<vector<int> > MyThreadSafeVectorInt(new vector<int>);
MyThreadSafeVectorInt.GetLockedObject()->push_back(123);
cout << MyThreadSafeVectorInt.GetLockedObject()->at(0) << endl;

//An instance of RefLock can be create to lock the object for the duration of a function.
Example Usage
ThreadSafeObject<string> MyThreadSafeString(new string);

string SomeFunction()
{
ThreadSafeObject<string>::RefLock MyLockedString = MyThreadSafeString.GetLockedObject();
MyLockedString->operator=("Hello World");
return MyLockedString->substr(6);
}

//The destructor for RefLock automatically unlocks the object, so an explicit unlock call
//is not required.
*/

#ifndef THREADSAFEOBJECT_H_HEADER_GUARD_
#define THREADSAFEOBJECT_H_HEADER_GUARD_

template<class T>
class ThreadSafeObject
{
public:
     ThreadSafeObject(T* type):m_type(type){InitializeCriticalSection(&m_cs);}
     ~ThreadSafeObject()
     {
          EnterCriticalSection (&m_cs);
          delete m_type;m_type=NULL;
          LeaveCriticalSection(&m_cs);
          DeleteCriticalSection(&m_cs);
     }
     class RefLock
     {
     public:
          RefLock(T* type, CRITICAL_SECTION &cs):m_type(type), m_cs(cs){ EnterCriticalSection (&m_cs);}
          RefLock(const RefLock& Src):m_type(Src.m_type), m_cs(Src.m_cs){ EnterCriticalSection (&m_cs);}
          ~RefLock(){LeaveCriticalSection(&m_cs);}
          inline T* operator->() const{return m_type;}
          inline T& operator*() const{return m_type;}
          T* m_type;
     private:
          CRITICAL_SECTION &m_cs;
     };
     RefLock GetLockedObject()
     {
          return RefLock(m_type, m_cs);
     }
private:
     T* m_type;
     CRITICAL_SECTION m_cs;
     ThreadSafeObject(const ThreadSafeObject&);
     ThreadSafeObject& operator=(const ThreadSafeObject&);
};

#endif //!THREADSAFEOBJECT_H_HEADER_GUARD_
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭