Subj : Re: Can C++ local static objects be made thread safe? To : comp.programming.threads From : Gianni Mariani Date : Fri Jan 21 2005 07:52 pm David Schwartz wrote: > "Gianni Mariani" wrote in message > news:iaudnW0LQIcam2zcRVn-ig@speakeasy.net... .... >>#define MTSafeStatic( Type, Name, Initializer ) \ >> static Type * x_ ## Name; \ >> Type * xlocal_ ## Name = x_ ## Name; \ >> \ >> ThreadLocal m_val; \ >> \ >> if ( ! m_val ) \ >> { \ >> MemoryBarrierSyncReads(); \ >> } \ >> \ >> if ( ! xlocal_ ## Name ) \ >> { \ >> Lock l_lock( StaticInitializerMutex ); \ >> \ >> if ( ! x_ ## Name ) \ >> { \ >> static Type v_ ## Name Initializer; \ >> \ >> MemoryBarrierSyncWrites(); \ >> x_ ## Name = & v_ ## Name ; \ >> xlocal_ ## Name = & v_ ## Name; \ >> } \ >> } \ >> \ >> m_val = true; \ >> \ >> Type & Name = * xlocal_ ## Name; \ >>// End macro > > > This isn't quite right. Another thread could see 'm_val' as true, and > the 'xlocal' as non-NULL and still not see the writes inside 'x'. You need a > memory barrier in every possible case, unfortunately. Not all architectures > provide a way for one thread to force another thread to see something. Just a minute - how can that be. On the first time through, a memory barrier sync is done. Worst case, you can't come out of this code normally without the construction being completed. Once you decide that you're locking the mutex, I assume barriers are looked after. The m_val value is thread local, meaning each thread executed the memory barrier at least once - once the memory barrier is synced once, why would it need to be synced again ? If it did, somthing much more serious is broken. .