SandaysComing 2015-01-27 05:33 采纳率: 0%
浏览 1584
已采纳

用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函数中,两条线程启动前构造好单例。
还有就是析构,主函数都结束了也没有调用析构

  • 写回答

1条回答 默认 最新

  • oyljerry 2015-01-27 05:43
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大