Subj : Re: Can C++ local static objects be made thread safe? To : comp.programming.threads From : SenderX Date : Thu Jan 20 2005 12:48 pm > #define MTSafeStatic( Type, Name, Initializer ) \ > static Type * volatile x_ ## Name; \ > \ > if ( ! x_ ## Name ) \ > { \ > Lock l_lock( StaticInitializerMutex );\ > \ > if ( ! x_ ## Name ) \ > { \ > static Type v_ ## Name Initializer; \ > \ > x_ ## Name = & v_ ## Name ; \ > } \ > } \ > \ > Type & Name = * x_ ## Name; \ Your totally breaking the producer/consumer relationship wrt memory visibility. 1: static T volatile *shared = 0; 2: T *local = shared; 3: ac_cpu_mb_consumer_depends(); /* Sync with 10 */ 4: if ( ! local ) 5: { ac_mutex_lock( &static_mutex ); 6: local = shared; 7: ac_cpu_mb_consumer_depends(); /* Sync with 10 */ 8: if ( ! local ) 9: { local = new T; 10: ac_cpu_mb_producer(); /* Sync with 3 & 7 */ 11: shared = local; /* Make visible to 4 & 8 after sync */ 12: } 13: ac_mutex_unlock( &static_mutex ); 14: } 15: return local; This must be compiled so the code sequence is executed in the "exact" order shown! All calls prefixed with 'ac_' are from my library. .