简体   繁体   中英

Thread safety SingletonHolder performance?

In the POCO framework, the SingletonHodler is a template class for managing sigleton objects. The method which obtains the singleton object is :

    S* get()
    /// Returns a pointer to the singleton object
    /// hold by the SingletonHolder. The first call
    /// to get will create the singleton.
{
    FastMutex::ScopedLock lock(_m);
    if (!_pS) _pS = new S;
    return _pS;
}

The problem is this method always uses the mutex to ensure that there isn't more than one singleton object created in multithreaded environment. I think it is appropriate to synchronize in the first time the method called. It will waste resources if we synchronize after that. I know Double check locking can resolve this problem but it may be broken .

My question is whether POCO would rather ensure the safety in multithreaded environment than save resources?

Following your thoughts nothing is stopping you to use it like:

   MySingleton* s = mySingletonHolder.get();
   s->doSomething(); //no locking
   ...
   s->doSomething(); //no locking

Obviously, if you use it always like:

   mySingletonHolder.get()->doSomthing();
   ...
   mySingletonHolder.get()->doSomthing();

You will always have the lock overhead.

BTW, If your are using your singleton instance in a multi-thread scenario you should guarantee that the call to doSomething() is thread-safe. Doing only mySingletonHolder.get()->doSomthing(); do not guarantee you that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM