<div dir="ltr">I&#39;ve been looking over the thread safe additions to localtime.c, and have a few comments.<div><br></div><div>1. Use of C&#39;s &#39;volatile&#39; declaration is not sufficient to implement fully thread-safe double-checked locking. The complications are confusing and subtle. Here is a paper that goes into the question in depth: <a href="http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf">http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf</a></div><div><br></div><div>The bottom line is that doing it right needs memory barrier operations - a read acquire and write release or equivalent for the flag variable being tested. Volatile does not guarantee these. C11 has the necessary functions, but is not yet widely available. [ <a href="http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1570.pdf">http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1570.pdf</a> ]  Compilers mostly have non-standard extensions available that will do the job, often modeled after those in gcc.</div><div><br></div><div>2. The function gmtcheck() needs to recheck the gmt_is_set flag after acquiring the lock. As it stands, multiple threads could replicate the initialization, overwriting a previously set gmtptr in the process. This is unrelated to the volatile question.</div><div><br></div><div>3.  The volatile variable lcl_is_set is referenced while not holding the lock in only one place, in localtime_r(). And from there the function localtime_tzset() is unconditionally called, which unconditionally acquires the lock.  With minor refactoring, all access to lcl_is_set could be from code that is holding the lock, which would allow lcl_is_set to be an ordinary variable with no special thread safety considerations.</div><div><br></div><div>If it were up to me, I would probably remove use of the double-checked idiom, and rely on solely lock(). Slightly slower, but simple, portable and safe. The alternative is to #define some compiler-dependent atomic operations.</div><div><br></div><div>  Thanks,<br></div><div><br></div><div>   -- Andy Heninger</div></div>