使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_
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值