Cppunit 源码 SynchronizedObject

运用C++的构造,析构进行,加锁解锁。在函数进入的时候定义临时变量。任何一个分支推出的时候都会调用析构函数。避免多分支出现的问题。 

 1 #ifndef CPPUNIT_SYNCHRONIZEDOBJECT_H
 2 #define CPPUNIT_SYNCHRONIZEDOBJECT_H
 3 
 4 #include <cppunit/Portability.h>
 5 
 6 
 7 CPPUNIT_NS_BEGIN
 8 
 9 
10 /*! \brief Base class for synchronized object.
11  *
12  * Synchronized object are object which members are used concurrently by mutiple
13  * threads.
14  *
15  * This class define the class SynchronizationObject which must be subclassed
16  * to implement an actual lock.
17  *
18  * Each instance of this class holds a pointer on a lock object.
19  *
20  * See src/msvc6/MfcSynchronizedObject.h for an example.
21  */
22 class CPPUNIT_API SynchronizedObject
23 {
24 public:
25   /*! \brief Abstract synchronization object (mutex)
26    */
27   class SynchronizationObject
28   {
29     public:
30       SynchronizationObject() {}
31       virtual ~SynchronizationObject() {}
32 
33       virtual void lock() {}
34       virtual void unlock() {}
35   };
36 
37   /*! Constructs a SynchronizedObject object.
38    */
39   SynchronizedObject( SynchronizationObject *syncObject =0 );
40 
41   /// Destructor.
42   virtual ~SynchronizedObject();
43 
44 protected:
45   /*! \brief Locks a synchronization object in the current scope.
46    */
47   class ExclusiveZone
48   {
49     SynchronizationObject *m_syncObject;
50 
51   public:
52     ExclusiveZone( SynchronizationObject *syncObject ) 
53         : m_syncObject( syncObject ) 
54     { 
55       m_syncObject->lock(); 
56     }
57 
58     ~ExclusiveZone() 
59     { 
60       m_syncObject->unlock (); 
61     }
62   };
63 
64   virtual void setSynchronizationObject( SynchronizationObject *syncObject );
65 
66 protected:
67   SynchronizationObject *m_syncObject;
68 
69 private:
70   /// Prevents the use of the copy constructor.
71   SynchronizedObject( const SynchronizedObject &copy );
72 
73   /// Prevents the use of the copy operator.
74   void operator =( const SynchronizedObject &copy );
75 };
76 
77 
78 CPPUNIT_NS_END
79 
80 #endif  // CPPUNIT_SYNCHRONIZEDOBJECT_H

 

 1 #include <cppunit/SynchronizedObject.h>
 2 
 3 
 4 CPPUNIT_NS_BEGIN
 5 
 6 
 7 SynchronizedObject::SynchronizedObject( SynchronizationObject *syncObject )
 8     : m_syncObject( syncObject == 0 ? new SynchronizationObject() : 
 9                                       syncObject )
10 {
11 }
12 
13 
14 SynchronizedObject::~SynchronizedObject()
15 {
16   delete m_syncObject;
17 }
18 
19 
20 /** Accept a new synchronization object for protection of this instance
21  * TestResult assumes ownership of the object
22  */
23 void 
24 SynchronizedObject::setSynchronizationObject( SynchronizationObject *syncObject )
25 { 
26   delete m_syncObject; 
27   m_syncObject = syncObject; 
28 }
29 
30 
31 CPPUNIT_NS_END

 

posted @ 2015-05-10 00:28  20130222  阅读(213)  评论(0编辑  收藏  举报