作者在 2008-09-30 23:12:01 发布以下内容
C++中,我们经常会用到静态变量,但对于这些静态变量的初始化,我们只能对其进行赋初值,不能像C#或是Java中那样,有一个静态初始化段来进行一些复杂的初始化工作。
举例来说,我有一个类,其成员变量会在多个线程中并发访问,所以我需要一个锁来保护数据一致性。于是有了这样的代码:
- class MyClass
- {
- public:
- void Foo()
- {
- ::EnterCriticalSection(&ms_lock);
- // operates m_mapValues
- ::LeaveCriticalSection(&ms_lock);
- }
- protected:
- std::map<int,std::string> m_mapValues;
- static CRITICAL_SECTION ms_lock;
- };
- CRITICAL_SECTION MyClass::ms_lock; // We can't call InitializeCriticalSection here
前几天从同事那里学到了一个技巧,只用很少的几行代码,就可以实现这个功能。感叹自己C++还没用精,东西其实都知道,就是在问题面前没能想到。
解决上面问题的办法:
- class CCriticalSection
- {
- public:
- CCriticalSection() { ::InitializeCriticalSection(&m_criticalSection); }
- ~CCriticalSection() { ::DeleteCriticalSection(&m_criticalSection); }
- void Lock() { ::EnterCriticalSection(&m_criticalSection); }
- void Unlock() { ::LeaveCriticalSection(&m_criticalSection); }
- protected:
- CRITICAL_SECTION m_criticalSection;
- };
- template <class LockObject>
- class ScopedLocker
- {
- public:
- ScopedLocker(LockObject& lockObject) : m_lockObject(lockObject) { m_lockObject.Lock(); }
- ~ScopedLocker() { m_lockObject.Unlock(); }
- protected:
- LockObject& m_lockObject;
- };
- class MyClass
- {
- public:
- void Foo()
- {
- ScopedLocker<CCriticalSection> locker(m_lockObject); // EnterCriticalSection will be called here
- // operates m_mapValues;
- } // LeaveCriticalSection will be called here
- protected:
- std::map<int, std::string> m_mapValues;
- static CCriticalSection m_lockObject;
- };
- CCriticalSection MyClass::m_lockObject; // InitializeCriticalSection will be called here