I got some private feedback to the effect that if two threads call Ref() at the same time, they may get back different references, and one object may end up being memory leaked. This is an acceptable outcome for the kind of usage this class was designed for.
If someone wants to use the Singleton class directly in their own application, where this isn't an acceptable outcome, they can always do their own locking around the Ref() calls. Please let me know if there are any other problems, like the ones that Pavel found (thanks, btw). -------------------------------------------------- From: "Wei Dai" <[email protected]> Sent: Thursday, September 24, 2009 8:20 PM To: "Crypto++ Users" <[email protected]> Subject: Re: Race condition in singleton > > I'd rather not do singleton init at startup if possible. Can you please > take > a look at this version of Singleton::Ref() and see if it still has a race > condition? > > template <class T, class F, int instance> > const T & Singleton<T, F, instance>::Ref(CRYPTOPP_NOINLINE_DOTDOTDOT) > const > { > static volatile simple_ptr<T> s_pObject; > T *p = s_pObject.m_p; > > if (p) > return *p; > > T *newObject = m_objectFactory(); > p = s_pObject.m_p; > > if (p) > { > delete newObject; > return *p; > } > > s_pObject.m_p = newObject; > return *newObject; > } > > I also changed simple_ptr's destructor to set m_p = NULL after deletion, > so > double deletes should be harmless: > > ~simple_ptr() {delete m_p; m_p = NULL;} > > Do I need to do something stronger to prevent the m_p = NULL from being > optimized away? > > > > > --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the "Crypto++ Users" Google Group. To unsubscribe, send an email to [email protected]. More information about Crypto++ and this group is available at http://www.cryptopp.com. -~----------~----~----~----~------~----~------~--~---
