[cpp-threads] Globals and Threads

Peter A. Buhr pabuhr at plg.uwaterloo.ca
Mon Oct 24 19:26:46 BST 2005


   From: Andrei Alexandrescu <andrei at metalanguage.com>
   Reply-To: C++ threads standardisation <cpp-threads at decadentplace.org.uk>
   Sender: cpp-threads-bounces at decadentplace.org.uk

   > While thinking about globals, I stumbled across the problem of static
   > locals. What is the implication when a function with local static variables
   > is called from several threads? This could result in race conditions if
   > one thread is updating the variable while the other reads from the
   > variable. Simply put, normal local static variables are not thread-safe.

   We've talked about this. No shared data is automagically thread-safe btw 
   :o). As far as I remember, there were three possible solutions that we 
   discussed:
   ...
   3. Leave things as they are and allow users to guard things manually 
   with a statically-initialized bool:

   Widget * Foo() {
      static bool initialized = false;
      static Widget result = 0;
      if (std::assign_once(initialized, true)) {
	// Code executed only once
	static Widget w;
	result = &w;
      }
      return result;
   }

   I incline towards 3 because it's most flexible and doesn't require 
   syntax changes.

I agree with Andrei. I don't think the compiler can truly understand what a
user wants at this level, so it would be guessing.  There are many explicit
solutions to this problem, and a user can pick one that best suits their needs.



More information about the cpp-threads mailing list