5

Is the following code thread-safe? (Using a IIFE to initialize a static local variable.)

int MyFunc(){

static int Val = ([]()
   {
   return 1 + 2 + 3 + 4; // Real code is more complex, but thread-safe
   })();

return Val;

}
RainingChain
  • 7,397
  • 10
  • 36
  • 68
  • Very similar [question](https://stackoverflow.com/questions/11939484/is-initialization-of-local-static-function-object-thread-safe), possibly a duplicate. – 1201ProgramAlarm Nov 15 '19 at 03:25

1 Answers1

6

Yes. C++11 (and above) guarantees no data races between multiple threads trying to initialize a static local variable. If the code inside your lambda is thread-safe, the initialization will be as well.

Using a lambda, function call, or constructor doesn't change the thread-safety of the initialization.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
  • 1
    what do you mean by `If the code inside your lambda is thread-safe` -- shouldn't the lambda be called only from the first thread reaching the initializer ? – Andre Holzner Feb 18 '21 at 10:53
  • 1
    @AndreHolzner Correct, but the code inside the lambda might for instance call functions that aren’t reentrant, and which are being called concurrently elsewhere. – Konrad Rudolph Oct 26 '21 at 11:27