回调到单例类

Dan*_*anS 1 c++ singleton multithreading

我正在使用一个单例类,其中一个线程调用单例.在审查期间我被问到为什么我使用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 
}
Run Code Online (Sandbox Code Playgroud)

那两者之间的速度有什么显着差异吗?

threadWrapper是在现有代码库中强制执行的,我不允许使用boost.

我的理由是,如果我们需要使这不是单身,那么就需要更少的改变.

Pup*_*ppy 5

速度差异几乎不存在.

至于代码质量,Singletons是非常可怕的,我个人会丢掉这两种形式,特别是在线程环境中.然而,假设为时已晚.

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

编辑:如果你坚持使用现有的设计,那么第二个版本肯定比第一个版本好,而且速度不慢.即使你有现有的代码依赖于Singleton,那么重构你不能依赖它的东西绝对更好.