c++ - 回调到单例类

标签 c++ multithreading singleton

我正在使用一个带有调用单例的线程的单例类。在审查期间有人问我为什么使用 this 指针而不是单例实例。

带有建议更改的我的代码。

class myClass : public threadWrapper
{
public:
    static myClass& instance()
    {
        static myClass instance;
        return instance;
    }

    // This is the callback that I have implemented
    static void callback(void *me)
    {
        if (me != NULL)
            static_cast<myClass*>(me)->doCallback();
    }

    // This is the suggested callback
    static void callback2(void *me)
    {
        instance().doCallback();
    }

    // caller gets instance and then calls initialise()
    int initialise()
    {  
        if (initialised)
            return ERROR_ALREADY_INITIALISED;

        // Initialise the class

        // my thread startup call
        // thread wrapper class initialisation that calls pthread_create that runs the callback method with this as a parameter
        // priority is a global value that difines the relative priority of the various threads.
        threadWrapper::Initialise(priority, callback, this);
        initialised = true;

    }
private:
    myClass() : initialised(false) {;}

    void doCallback(void);

    bool initialised;

    static const int 
}

那么两者在速度上有什么显着差异吗?

现有代码库中强制使用 threadWrapper,我不允许使用 boost。

我的理由是,如果我们需要让它不是单例,那么需要的更改会更少。

最佳答案

速度差异几乎不存在。

至于代码质量,单例非常可怕,我个人会放弃这两种形式,尤其是在线程环境中。然而,假设为时已晚。

问题是,如果您要传递一个指向该对象的指针,为什么不首先将该对象设为全局对象呢?如果你是,它至少应该是强类型的。然后,您只是……将成员方法包装在静态方法中?何必呢?任何拥有该类指针的人都可以首先调用它的方法。这太疯狂了。

编辑:如果您坚持使用现有的设计,那么第二个版本肯定比第一个好,而且速度也不慢。即使您现有的代码依赖于 Singleton,那么最好重构您可以不依赖它的代码。

关于c++ - 回调到单例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6537226/

相关文章:

ios - Singleton 模式在 Swift 中使用得好吗?

c++ - 为什么我不能将 const 左值引用绑定(bind)到返回 T&& 的函数?

java - java中异步进程的技术和设计

c++ - 如何正确增加 C++11 std::atomic?

multithreading - 为什么鼓励 Julia 中的去向量化?

objective-c - 当我使用 static 实现单例时,有什么可能出错的地方吗?

java - 通过 C++/Java 进行音频编辑

c++ - 为每个算法传递多个函数

c++ - 无符号字符模板值溢出

kotlin - 什么时候适合在 Micronauts 中使用 @Singleton 和 @Prototype?