patterncppMinor
Resource locker in Qt
Viewed 0 times
lockerresourcestackoverflow
Problem
The idea is to lock resources in C# or Java using Qt:
Now I see the problem with deleting
resourcelocker.h
resourcelocker.cpp
Usage:
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
#include
#include
class ResourceLocker : public QObject
{
Q_OBJECT
public:
friend class ResourceWatcher;
explicit ResourceLocker(QObject *parent = 0);
~ResourceLocker();
bool lock();
private:
static QHash resources;
QSemaphore * sem;
QObject * expectedParent;
bool doubleLock;
signals:
public slots:
};
#define _LOCK(object) for (ResourceLocker locker((object)); locker.lock(); )
#endif // RESOURCELOCKER_Hresourcelocker.cpp
#include "resourcelocker.h"
#include
#include
#include
#include
QHash ResourceLocker::resources;
class ResourceWatcher: public QObject
{
public:
explicit ResourceWatcher(QObject * parent):
QObject(parent)
{
//qDebug()available()>0)
{
//unlocked
ResourceLocker::resources.remove(parent());
delete sem;
}
else
{
//locked
ResourceLocker::resources.remove(parent());
}
//qDebug()acquire();
return true;
}
ResourceLocker::~ResourceLocker()
{
QMutex internalMutex;
QMutexLocker locker(&internalMutex);
//qDebug()release();
if (!resources.values().contains(sem))
delete sem;
}Usage:
_LOCK(smth)
{
//prcoess with smth locked
}Solution
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:
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(&mutex);
/* code */
}Code Snippets
// Note: Braces for scope. "mutex" could optionally be declared static, or as a class member.
{
QMutexLocker lock(&mutex);
/* code */
}Context
StackExchange Code Review Q#4886, answer score: 2
Revisions (0)
No revisions yet.