Resource locker in Qt The idea is to lock resources in C# or Java using Qt:

lock(obj){/*process with locked obj*/}`


Now I see the problem with deleting obj under lock().

resourcelocker.h

#ifndef RESOURCELOCKER_H
#define RESOURCELOCKER_H

#include &lt;QObject&gt;
#include &lt;QHash&gt;
#include &lt;QSemaphore&gt;

class ResourceLocker : public QObject
{
    Q_OBJECT
public:

    friend class ResourceWatcher;
    explicit ResourceLocker(QObject *parent = 0);
    ~ResourceLocker();

    bool lock();

private:
    static QHash&lt;QObject*,QSemaphore*&gt; resources;
    QSemaphore * sem;
    QObject * expectedParent;
    bool doubleLock;

signals:

public slots:

};

#define _LOCK(object) for (ResourceLocker locker((object)); locker.lock(); )

#endif // RESOURCELOCKER_H


resourcelocker.cpp

#include "resourcelocker.h"
#include &lt;QMutex&gt;
#include &lt;QMutexLocker&gt;
#include &lt;QSemaphore&gt;
#include &lt;QDebug&gt;

QHash&lt;QObject* ,QSemaphore*&gt; ResourceLocker::resources;

class ResourceWatcher: public QObject
{
public:
    explicit ResourceWatcher(QObject * parent):
        QObject(parent)
    {
        //qDebug()&lt;&lt;"creating watcher";
    }

    ~ResourceWatcher()
    {
        QSemaphore * sem = ResourceLocker::resources.value(parent(),NULL);
        if (sem-&gt;available()&gt;0)
        {
            //unlocked
            ResourceLocker::resources.remove(parent());
            delete sem;
        }
        else
        {
            //locked
            ResourceLocker::resources.remove(parent());
        }
        //qDebug()&lt;&lt;"removing sem";

    }
};

ResourceLocker::ResourceLocker(QObject *parent) :QObject(),expectedParent(parent),doubleLock(false)
{
}

bool ResourceLocker::lock()
{
    static QMutex internalMutex;
    {
        QMutexLocker locker(&amp;internalMutex);

        if (doubleLock)
            return false;
        doubleLock = true;
        //qDebug()&lt;&lt;&amp;expectedParent;

        sem = resources.value(expectedParent,NULL);
        if (sem == NULL)
        {
            //qDebug()&lt;&lt;"Crearting sem";
            sem = new QSemaphore(1);
            resources.insert(expectedParent,sem);
            new ResourceWatcher(expectedParent);
        }
    }
    //qDebug()&lt;&lt;"acquiring";
   sem-&gt;acquire();
   return true;
}

ResourceLocker::~ResourceLocker()
{
    QMutex internalMutex;
    QMutexLocker locker(&amp;internalMutex);
    //qDebug()&lt;&lt;"releasing";
    sem-&gt;release();
    if (!resources.values().contains(sem))
        delete sem;
}


Usage:

_LOCK(smth)
    {
        //prcoess with smth locked

    }
There reason languages like Java has that feature is because they don't have RAII like C++ does.

I don't quite see how that is better than simply:

// Note: Braces for scope. "mutex" could optionally be declared static, or as a class member.
{ 
    QMutexLocker lock(&amp;mutex);

    /* code */
}