我在自己的项目中使用线程安全的 QObject 单例,我想知道使用 QtConcurrent 而不是 QMutex'es 和 QThread's 创建它们是否正确。
这是我如何编写单例代码。
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;
}
};
这比以下更好吗?
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;
}
};
或者,还有其他更好的方法吗?
谢谢你。
注意:我正在单独处理共享实例销毁。
编辑:我希望共享实例位于主线程中。