c++ - safe way to get a singleton instance from multithreads -



c++ - safe way to get a singleton instance from multithreads -

method 1

datacenter* datacenter::getinstance() { static datacenter instance; homecoming &instance; }

method 2

datacenter* datacenter::getinstance() { if (!m_instanceflag) { m_instance = new datacenter(); m_instanceflag = true; } homecoming m_instance; }

i working on multi threaded programming , datacenter accessed more 1 thread. used have method 2 instance of datacenter , worked fine. noted need guard singleton instance beingness called multi threads.

my question first need guard singleton instance? or os me? sec questions that, first method right way singleton instance?

thanks in advance...

1.you need guard , if don't, of course, os wouldn't you. utilize next code thread-safety:

datacenter* datacenter::getinstance() { mutexlocker locker(datacenter::m_mutex); if(!m_instanceflag) { m_instance = new datacenter(); m_instanceflag = true; } homecoming m_instance; }

edit:

where mutexlocker this:

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.first method looks ok, not thread-safe.

c++ multithreading

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

c# - Can ProtoBuf-Net deserialize to a flat class? -

javascript - Change element in each JQuery tab to dynamically generated colors -