Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!news.glorb.com!news.astraweb.com!border6.newsrouter.astraweb.com!not-for-mail From: Gerhard Fiedler Subject: Re: Double check locking - are release and acquire fences enough for C++ memory model? Newsgroups: comp.programming.threads User-Agent: 40tude_Dialog/2.0.15.84 MIME-Version: 1.0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 8bit References: <9b219fb9-0b51-4c06-9398-d1e7ab878f7d@googlegroups.com> <511207c5$0$6565$9b4e6d93@newsspool3.arcor-online.net> Date: Wed, 6 Feb 2013 11:58:41 -0200 Message-ID: <1qaaqol9bs9d7.dlg@gelists.gmail.com> Lines: 24 Organization: Unlimited download news at news.astraweb.com NNTP-Posting-Host: 9106f9f3.news.astraweb.com X-Trace: DXC=lCRWaNj:nSndoV@f]470JnL?0kYOcDh@jEE63Zc8>Ueg[ln[ static T* ptr = NULL; > static Mutex mtx; > > T* get_singleton_T() > { if (!ptr) // First check, race condition accepted > { mtx.lock(); // wait for mutex, full mem bar > if (!ptr) // the double check > ptr = new T(); // create singleton > mtx.release(); // release mutex, full mem bar > } > return ptr; > } > > With this code a dependency of singleton X to singleton Y is no problem > at all, since the getter will never return incomplete objects. A side question: Isn't this a broken implementation? Is it not possible that ptr is assigned the address of the uninitialized memory for T before T is initialized -- which then could lead to returning uninitialized memory in a second thread? Gerhard