CIDLib Core Class Reference: TLocker

Class: TLocker


Facility: CIDLib.Dll
Header: CIDLib_Lock.Hpp
Derived From: TCIDObject

TLocker is a specialized janitor class, for locks. It is implemented in terms of the MLockable mixin class, therefore it can lock anything that is derived from MLockable. The constructor takes a pointer to some lockable object, locks it, then stores the pointer away. When the lock object is destroyed, it will unlock the object it has locked. This provides an extremely safe mechanism for managing locks within a called function or any block of code. Upon exit of that block, whether by return or exception, the lock object will be destructed and the lock undone. Put a reference to the term 'janitor' >

Here is an example. It is trivial but shows exactly how lockers are used. This is an incredibly safe and clean mechanism for locking things, dontcha think?

    //
    //  We assume mtxFooLock.Create() gets called during init, to
    //  create the unnamed semaphore. Or mtxFooLock.Open() to open
    //  a named semaphore perhaps.
    //
    TMutexSem       mtxFooLock;
    tCIDLib::TCard4 c4FooCount = 0;

    void IncFooCount()
    {
        // Lock the semaphore while in this function
        TLocker lockFoo(mtxFooLock);

        // Update controlled variables now
        c4FooCount++;

        // When lockFoo destructs mtxFooLock is unlocked
    }

Constructors

There is only one available constructor, which is to take a pointer to a lockable object and a timeout value to wait for the lock to succeed. If the lockable target does not support a timeout, the it should return return immediately if the lock cannot be accomplished. In either case, the caller just knows that it could not lock it. If the lock fails, then an exception will be thrown by whatever underlying locking mechanism was used for the locking. Probably it will be a semaphore timeout, but not necessarily.
    TLocker
    (
                MLockable* const        plockTarget
        , const tCIDLib::TCard4         c4TimeOut = tCIDLib::c4MaxCard
    );

Caveats/Gotchas

Keep these issues in mind when using TLocker objects:
  1. You obviously don't want to let the locker have a longer life than the thing that its locking, since the locker has a pointer to it and is doing to call the unlock method of the object upon its own death. If the other object has destructed since then, then powie, wham, bam Batman, you're gonna crash.
  2. For the most part, they are always used on the stack to protect something during the life of some scope block. For instance, if you create one upon entry to a function, it will enforce the lock for the life of that function. Within any set of curly braces, it locks until that block is exited.

Public Methods

N/A This guy has no public methods other than the standard RTTI methods. It just constructs and destructs, which is all it exists for anyway.
CIDCorp
Dean Roddey
Internet: droddey@ng.netgate.net
CIS: 72170,1614