Locked

Files CCore/inc/gadget/Locked.h CCore/src/gadget/Locked.cpp

This simple Helper Class is useful to implement a locked access to some object. It is an object pointer. In the constructor it locks the given mutex and in the destructor it unlocks one.


template <class Mutex,class T>
class Locked : Mutex::Lock
 {
   T &obj;
 
  public:
 
   Locked(Mutex &mutex,T &obj_) : Mutex::Lock(mutex),obj(obj_) {}
   
   ~Locked() {}
   
   // object ptr
   
   T * getPtr() const { return &obj; }
   
   T * operator -> () const { return &obj; }
   
   T & operator * () const { return obj; }
 };

Here is an example:


Mutex mutex;

Class obj;

Locked<Mutex,Class>(mutex,obj)->method();

The method above is called under the mutex protection.