tsc_LockInstance

This class is primarily for internal use by the tsc_Lock macro, however it may be used in its own right.  The purpose of tsc_LockInstance is to create a lock on a given object when the instance is constructed, and to release the lock when the instance is destroyed.  Since a locally constructed C++ object is destroyed when control leaves the code block in which it was defined, this allows a lock to be created which spans a given block of code.

This purpose is to lock objects against concurrent changes or accesses by other threads.  Further general information about locking can be found in tsc_Lock.

Public methods

tsc_LockInstance (tsc_Object* anyObject);

The constructor must be passed a pointer to the object to be locked.  Note that this only has to be some common object to which all locks refer, and not necessarily the object which is being protected, although it is preferable to use the protected object for clarity.

void Unlock();

Prematurely releases the lock placed by the constructor. Calling this is usually unnecessary, since the destructor will automatically release the lock.

virtual ~tsc_LockInstance ();

Destruction releases the lock placed by the constructor. By placing the definition of tsc_LockInstance within a { code block }, the lock will be automatically acquired and released.

Notes

More general information about locking can be found on the page describing the tsc_Lock macro.  

Example

class ProtectedObject : public tsc_Object

{

    // some members...

};


// Protecting an object for the life of a function.

void SafelyModify (ProtectedObject& pob)

{

    tsc_LockInstance lock (&pob);

    // ...Modify pob as required...

    // Upon function exit, the instance of 'lock' will be destroyed and the lock on 'pob' is released.

}


// or, protecting an object for a specific duration...

void Function (ProtectedObject& pob)

{

    // The function may do some preliminary work...


    {

        tsc_LockInstance lock (&pob);


        // ...Modify pob as required...


        // Upon exit from the block, the instance of 'lock' will be destroyed and the lock on 'pob' is released.

    }


    // The function may do further work here


}