Subj : Re: Can C++ local static objects be made thread safe? To : comp.programming.threads From : David Schwartz Date : Thu Feb 10 2005 04:51 pm "Giancarlo Niccolai" wrote in message news:95e4efda.0502101630.6e6c144d@posting.google.com... >> You have still not shown what will break under the synchronized >> semantics. And this is because nothing will break that wasn't >> already broken. > > Metacode: > > static int CountOfItems = 0; > static the_reentrant_mutex; > > class Item { > > Item() { > the_reentrant_mutex.lock(); > CountOfItems ++; > the_reentrant_mutex.unlock(); > } > }; > > // Change this with your favorite static initializer method. > Item &cofu() { > static Item *the_item = 0; > if ( the_item == 0 ) { > the_item = new Item(); // compiler lock here. > } > return the_item; > } > > void thread_func_1() > { > Item *i = &cofu(); > // do something > } > > void thread_func_2() > { > // this threads wants to create a new Item, but without > // changing the count. > the_reentrant_mutex.lock(); > int old_count = CountOfItems; > Item *i = &cofu(); > CountOfItems = old_count; > the_reentrant_mutex.unlock(); > // use I. > } This code is already broken. The '&cofu()' method may modify '*the_item', so must be called while holding some sort of lock. The 'thread_func_1' function calls '&cofu' without holding any lock, so its interaction with 'thread_func_2' is undefined under POSIX. DS .