回调到singleton类

Callback into singleton class

本文关键字:singleton 回调      更新时间:2023-10-16

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

我的代码和建议的更改。

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非常糟糕,我个人会放弃这两种形式,,尤其是在线程环境中。然而,假设现在已经太晚了。

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

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