Using C + + 's construction, the destruction is carried out, and lock is unlocked. Defines a temporary variable when the function enters. Destructors are called when any one branch is launched. Avoid problems with multiple branches.
1 #ifndef Cppunit_synchronizedobject_h2 #defineCppunit_synchronizedobject_h3 4#include <cppunit/Portability.h>5 6 7 Cppunit_ns_begin8 9 Ten /*! \brief Base class for synchronized object. One * A * Synchronized object is object which members is used concurrently by Mutiple - * threads. - * the * This class define the class Synchronizationobject which must be subclassed - * To implement an actual lock. - * - * Each instance of this class holds a pointer on a lock object. + * - * See src/msvc6/mfcsynchronizedobject.h for an example. + */ A classCppunit_api Synchronizedobject at { - Public: - /*! \brief Abstract Synchronization object (mutex) - */ - classSynchronizationobject - { in Public: - Synchronizationobject () {} to Virtual~Synchronizationobject () {} + - Virtual void Lock() {} the Virtual voidunlock () {} * }; $ Panax Notoginseng /*! Constructs a Synchronizedobject object. - */ theSynchronizedobject (Synchronizationobject *syncobject =0 ); + A ///destructor. the Virtual~Synchronizedobject (); + - protected: $ /*! \brief Locks A synchronization object in the current scope. $ */ - classExclusivezone - { theSynchronizationobject *M_syncobject; - Wuyi Public: theExclusivezone (Synchronizationobject *SyncObject) - : M_syncobject (syncobject) Wu { -M_syncobject->Lock(); About } $ -~Exclusivezone () - { -M_syncobject->unlock (); A } + }; the - Virtual voidSetsynchronizationobject (Synchronizationobject *syncobject); $ the protected: theSynchronizationobject *M_syncobject; the the Private: - ///Prevents the use of the copy constructor. inSynchronizedobject (ConstSynchronizedobject ©); the the ///Prevents the use of the copy operator. About void operator=(ConstSynchronizedobject ©); the }; the the + Cppunit_ns_end - the #endif //Cppunit_synchronizedobject_h
1#include <cppunit/SynchronizedObject.h>2 3 4 Cppunit_ns_begin5 6 7Synchronizedobject::synchronizedobject (Synchronizationobject *SyncObject)8: M_syncobject (SyncObject = =0?Newsynchronizationobject ():9 SyncObject)Ten { One } A - -synchronizedobject::~Synchronizedobject () the { - DeleteM_syncobject; - } - + - /** Accept A new synchronization object for protection of this instance + * TestResult assumes ownership of the object A */ at void -Synchronizedobject::setsynchronizationobject (Synchronizationobject *SyncObject) - { - DeleteM_syncobject; -M_syncobject =SyncObject; - } in - toCppunit_ns_end
Cppunit Source Synchronizedobject