Subj : Re: Can C++ local static objects be made thread safe? To : comp.programming.threads From : Giancarlo Niccolai Date : Sat Feb 05 2005 12:09 am Marcin 'Qrczak' Kowalczyk wrote: > Giancarlo Niccolai writes: > >> To put that thing in a compiler, you have to mathematically demonstrate >> that: >> >> 1) ALL ever possible ST code can be made threadsafe by just adding a >> mutex at its initialization code. >> 2) ALL ever possible MT code won't be broken by your "help". > > No, 1 is not necessary for this change to be useful. And I believe 2 is > true. 1 is necessary for this change not to be switchable, but provided as a required standard. About 2 it is not a matter of believing, its a matter of mathematically demonstrate it. > >> Suppose that read_unicode_database_from_file() requires ANOTHER static >> initializer, or is replaced in the MT code with something different. In >> example, suppose that read_unicode_database_from_file() requires a locked >> variable to be prepared by the thread that calls >> lookup_unicode_char_by_name(). Then, chances are that >> read_unicode_database_from_file() will deadlock. > > If there was a cyclic dependency between local static objects, then the > library would have been already broken in a single-threaded environment. The cyclic dependency is introduced in MT code; ST code cannot have cyclic dependency. Thus, it does not need this kind of protection. > > I claim that it doesn't break code which is correct in ST. In fact. It doesn't break code that is safe under ST; it break that code if it needs some update in MT. Ad usually it does, or you would stay in ST. > >> You can EASILY avoid this situation by calling >> lookup_unicode_char_by_name() before any thread is started; you won't >> need any synchronization thereafter. > > This defeats the advantage of lazy initialization. Lazy initialization advantages 1) are not that much important to break working code and 2) can be kept anyhow by doing the lock you want do do implicitly in an explicit way. If you are explicit, then you know what you are meaning, and hopefully also what you are doing. In example, are you really sure that it's a "smart" programming technique to open and setup a database environment as a by-product of a very commonly used routine? How will you manage errors? With try-catches? are you really sure you want to try-catch all your access to a unicode-translation functions to prevent a lazy initialization failure to abort your program? Probably, the utility of lazy initialization in a program important enough to be multithreading (generally an high performance/availability server) is at least to be questioned. I repeat myself, but you are trying to solve an unexisting problem; correctly built MT programs just works another way, and ST programs going MT just must be redesigned in some area; so trying to make a ST program safe under MT with just a mutex here and there is not only impossible, it is also a totally useless exercice. Gian. .