7d2 Subj : Re: Can C++ local static objects be made thread safe? To : comp.programming.threads From : gniccolai Date : Thu Feb 10 2005 04:30 pm > 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. } .............................. if thread_func_1 and 2 goes together, you are deadlocked with the static initializer turned on. You can change cofu() with any static initializer you wish. Yes, Item class does not define a single dataset, but this fine. It's the way it has to be. There's nothing wrong with it. There's something wrong with the compiler locking its initialization. I don't like reentrant mutexes, but this is a valid MT technique under many circumstances. Crossing function calls is allowed if "function calls are trivial", even if discouraged. I had this test since I first presented the other example that deadlocked if using only one mutex for every static initializers, but I hoped you could see this simple thing by yourself, AT LEAST after that a similar case were given to you. You lost an occasion to seem smart, really. That was *really* my last. Adieu Giancarlo. . 0