I'm making use of thread-safe QObject singletons in my own project and I was wondering whether I'm doing right in creating them using QtConcurrent rather than QMutex'es and QThread's.
Here is how I'm managing to write singleton code.
class A : public QObject
{
Q_OBJECT
public:
A() {}
static A* sharedInstance() {
static QFuture<A*> helper = QtConcurrent::run([]() -> A* {
auto *instance = new A();
instance->moveToThread(qApp->thread());
return instance;
});
return (A*)helper;
}
};
Is this any way better than the following?
class A : public QObject
{
Q_OBJECT
public:
A() {}
static A* sharedInstance() {
static A* instance = 0;
static QMutex mtx;
mtx.lock();
if (!instance) {
instance = new A();
instance->moveToThread(qApp->thread());
}
mtx.unlock();
return instance;
}
};
Or, is there any other better way of doing this?
Thank you.
NOTE: I'm handling the shared instance destruction separately.
EDIT: I want the shared instances to be in the main thread.