FX::Generic::lockedAccessor< type > Struct Template Reference

#include <QThread.h>

List of all members.


Detailed Description

template<class type>
struct FX::Generic::lockedAccessor< type >

Holds a lock after a function exits.

As anyone familiar with multithreaded programming is aware, often one must make a choice between efficiency and thread-safety when writing member functions of a lockable class eg;

QStringList Class::foo() const
{
    QMtxHold h(this);
    return p->mystrings();
}
Above, one sees a whole copy of an entire FX::QStringList because you cannot return a reference for fear of the list being changed by another thread while the lock isn't held. Sometimes this is desirable, but what if one merely wanted to check if the list were empty? Then an entire copy is being performed just for it to be thrown away.

lockedAccessor solves this problem by extending the hold of the lock past the return of the member function:

Generic::lockedAccessor<const QStringList> Class::foo() const
{
    Generic::lockedAccessor<const QStringList> ret(p->mystrings(), this);
    // You can do stuff to ret as though it were p->mystrings()
    return ret;
}
This handles simple cases like class->foo().empty(), but you still must be careful - if you write QStringList list(class->foo()); then you are safe, but if you use the return directly then you can lose the lock inadvertently.

Definition at line 675 of file QThread.h.

Public Member Functions

 lockedAccessor (type &_val, const QMutex *m)
 lockedAccessor (type &_val, const QMutex &m)
 lockedAccessor (type &_val, const QRWMutex *m)
 lockedAccessor (type &_val, const QRWMutex &m)
 lockedAccessor (lockedAccessor &o)
lockedAccessoroperator= (lockedAccessor &o)
 ~lockedAccessor ()
type & operator * () const
type * operator-> () const


The documentation for this struct was generated from the following file:
(C) 2002-2009 Niall Douglas. Some parts (C) to assorted authors.
Generated on Fri Nov 20 18:37:59 2009 for TnFOX by doxygen v1.4.7