Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Is initializing a static local variable with a IIFE thread-safe?

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;

}
like image 666
RainingChain Avatar asked Nov 15 '19 02:11

RainingChain


People also ask

Is Initialization of static variable thread safe?

So yes, you're safe.

Is static variable thread safe?

Static variables are not thread safe. Instance variables do not require thread synchronization unless shared among threads. But, static variables are always shared by all the threads in the process.


1 Answers

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.

like image 117
Vittorio Romeo Avatar answered Oct 07 '22 02:10

Vittorio Romeo