安全的方式从多线程获取单例实例 [英] safe way to get a singleton instance from multithreads

查看:79
本文介绍了安全的方式从多线程获取单例实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方法1

DataCenter* DataCenter::getInstance()
{
    static DataCenter instance;
    return &instance;    
}

方法2 b

DataCenter* DataCenter::getInstance()
{
    if (!m_instanceFlag)
    {
        m_instance = new DataCenter();
        m_instanceFlag = true;
    }    
    return m_instance;      
}

我正在进行多线程编程,DataCenter将被超过一个线程。我曾经有方法2获得DataCenter的实例,它工作正常。但我注意到,我需要防止singleton实例被多线程调用。

I am working on a multi threaded programming and DataCenter will be accessed by more than one thread. I used to have method 2 to get the instance of DataCenter and it worked fine. But I noted that I need to guard the singleton instance from being called by multi threads.

我的问题是我真的需要保护单例实例吗?或者OS为我做这个?第二个问题是,第一个方法是正确的方式来获得单例实例吗?

My question is first do I really need to guard the singleton instance? or does OS do this for me? Second questions is that, is the first method a right way to get the singleton instance?

提前感谢...

推荐答案

需要保护它,即使你不,当然,操作系统不会为你做。使用以下代码来确保线程安全:

1.You do need to guard it and even if you don't, of course, OS wouldn't do it for you. Use following code for thread-safety:

DataCenter* DataCenter::getInstance()
{
    MutexLocker locker(DataCenter::m_mutex);
    if(!m_instanceFlag)
    {
        m_instance = new DataCenter();
        m_instanceFlag = true;
    }
    return m_instance;
}

编辑

其中 MutexLocker 如下所示:

class MutexLocker
{
    pthread_mutex_t &mutex;
    public:
    MutexLocker(pthread_mutex_t &mutex):mutex(mutex)
    {
        if(pthread_mutex_lock(&this->mutex)!=0)
            throw std::runtime_error("mutex locking filed");
    }
    ~MutexLocker(void)
    {
        if(pthread_mutex_unlock(&this->mutex)!=0)
            throw std::runtime_error("mutex unlocking filed");
    }
}

2.第一种方法看起来不错,安全。

2.First method looks ok, but not thread-safe.

这篇关于安全的方式从多线程获取单例实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆