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;
}
So yes, you're 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With