Subj : Re: Can C++ local static objects be made thread safe? To : comp.programming.threads From : Gianni Mariani Date : Fri Jan 21 2005 09:19 am Joseph Seigh wrote: .... > > In the sense that you can order memory accesses. They may differ in > which types of memory accesses they order, e.g. Sun sparc has more > types of memory barriers than Intel. It's not usually a problem > since you can use the stronger memory barrier if the more precise > one isn't available, e.g. an MFENCE on intel for an #LoadStore on > sparc, or #StoreStore on sparc for no membar on intel pentium. This > doesn't solve the compiler ordering problem though. > How about this scheme ? Would this be faster than the memory barrier example ? I suppose that depends on how fast the RW lock is. #define MTSafeStatic( Type, Name, Initializer ) \ static ReadWriteMutex xmutex_ ## Name; \ Type * xlocal_ ## Name; \ \ { \ // take a read lock \ ReadLock l_rlock; \ static Type * volatile x_marker; \ \ xlocal_ ## Name = x_marker; \ \ if ( ! xlocal_ ## Name ) \ { \ // unlock the read lock \ ReadUnLock l_runlock; \ // take the static initializer lock \ Lock l_lock( StaticInitializerMutex ); \ // take the write lock \ WriteLock l_wlock; \ \ xlocal_ ## Name = x_marker; \ if ( ! xlocal_ ## Name ) \ { \ static Type s_Obj Initializer; \ \ x_local ## Name = & s_Obj ; \ x_marker = & s_Obj; \ } \ } \ } \ \ Type & Name = * xlocal_ ## Name; \ // End macro .