头文件:

class ConnectionManager
{
public:
    static ConnectionManager *instance();

};

实现文件:

Q_GLOBAL_STATIC(ConnectionManager, connectionManager)

ConnectionManager *ConnectionManager::instance()
{
    return connectionManager();
}

 

使用:

ConnectionManager::instance()

 

// POD for Q_GLOBAL_STATIC
template <typename T>
class QGlobalStatic
{
public:
    QBasicAtomicPointer<T> pointer;
    bool destroyed;
};

 

// Created as a function-local static to delete a QGlobalStatic<T>
template <typename T>
class QGlobalStaticDeleter
{
public:
    QGlobalStatic<T> &globalStatic;
    QGlobalStaticDeleter(QGlobalStatic<T> &_globalStatic)
        : globalStatic(_globalStatic)
    { }

    inline ~QGlobalStaticDeleter()
    {
        delete globalStatic.pointer;
        globalStatic.pointer = 0;
        globalStatic.destroyed = true;
    }
};

 

 

#define Q_GLOBAL_STATIC_INIT(TYPE, NAME)                              \
    static QGlobalStatic<TYPE > this_##NAME = { Q_BASIC_ATOMIC_INITIALIZER(0), false }

#define Q_GLOBAL_STATIC(TYPE, NAME)                                     \
    Q_GLOBAL_STATIC_INIT(TYPE, NAME);                                   \
    static TYPE *NAME()                                                 \
    {                                                                   \
        if (!this_##NAME.pointer && !this_##NAME.destroyed) {           \
            TYPE *x = new TYPE;                                         \
            if (!this_##NAME.pointer.testAndSetOrdered(0, x))           \
                delete x;                                               \
            else                                                        \
                static QGlobalStaticDeleter<TYPE > cleanup(this_##NAME); \
        }                                                               \
        return this_##NAME.pointer;                                     \
    }

 

Q_GLOBAL_STATIC:

1、先通过Q_GLOBAL_STATIC_INIT声明一个静态的全局变量(this_##NAME ),并初始化为0

2、声明一个名字叫做全局变量(NAME)的static的函数,用来取得这个全局变量

3、如果这个变量没初始化且没删除,就通过testAndSetOrdered以原子方式创建

4、创建成功,再定义一个函数内的QGlobalStaticDeleter来清理这个全局变量

5、函数返回最后结果

 

qt在每个arch上面都实现了原子操作,移植时候修改src/corelib/arch/qatomic_ARCH.h

参考文档: Implementing Atomic Operations

相关文章:

  • 2022-12-23
  • 2021-06-04
  • 2021-10-25
  • 2022-12-23
  • 2021-10-10
  • 2022-12-23
  • 2022-01-31
猜你喜欢
  • 2022-02-16
  • 2022-12-23
  • 2021-09-06
  • 2021-06-27
  • 2022-12-23
  • 2021-10-03
  • 2022-12-23
相关资源
相似解决方案