用C++写的单例模式,问题求解

用C++写的单例模式,问题求解

问题描述:

阉割过的代码

class S

{

public:

        S* getInstance()
        {
                    if(instance==NULL)
                    {            
                               instance=new S();
                    }
                                return instance;
        };

        ~S(){cout<<"单例析构"<<endl};
    private:

        S()
        {
                    /*******省略多行*****/
                    cout<<"单例构造"<<endl;
        };

        S(const S& s);
        Log & operator = (const Log &);

        static S* instance;

        /****...................*****/

}

void* run1(void* arg)
{

        S* s1= S::getInstance();
        cout<<" s1="<<s1<<endl;
        for (int i = 0; i < 50; i++)
        {
                    /*****省略多行*****/
        }

}

void* run2(void* arg)
{

        S* s2= S::getInstance();
        cout<<" s2="<<s2<<endl;
        for (int i = 0; i < 50; i++)
        {
                    /*****省略多行*****/
        }

}

int main(int argc,char** argv)
{

        pthread_t th1;
        pthread_t th2;

        //S::getInstance();

        pthread_create(&th1, NULL, run1, NULL);
        pthread_create(&th2, NULL, run2, NULL);

        pthread_join(th1,NULL);
        pthread_join(th2,NULL);

}

运行几次发现,有时候两条线程的单例是不一样的。
原因可能是在getInstance()函数里,有一条线程通过NULL判断后还没来的及构造就被阻塞了,然后另一条也通过了NULL判断,造成了两次构造。

我能想到的解决方法只有在main函数中,两条线程启动前构造好单例。
还有就是析构,主函数都结束了也没有调用析构

你的单例不是线程安全的,所以不一定是真正意义的单例
http://lwzy-crack.blog.163.com/blog/static/9527204220091068526135/