Is a static variable created using a lambda thread-safe?

Viewed 109
    A& instA()
    {
        static A a = []{
              return A();
         }();
         return a;
    }

instA() returns a single static a; is this function multithread safe?

1 Answers

As mentioned in a comment, a simpler code that achieves the same is:

A& instA()
{
    static A a;
    return a;
}

Since C++11, this is thread-safe. No mutex needed inside this function. a will be created only once and different threads can get a reference to it.

However, don't make the mistake of believing the above solves all threading issues concerning a.

Two thread can do this:

  // thread A
  auto x = instA();

  // thread B
  auto y = instA();

But as soon as more than one thread accesses the instance and at least one writes, you need to synchronize the access. This is not thread safe:

  // thread A
  auto x = instA();
  x.foo = 42;

  // thread B
  auto y = instA();
  int y = x.foo;

In summary: Your instA is creating the instance in a thread safe-manner. Though, that does not imply that anything beyond creating the instance is thread safe. I would suggest to return a const A& instead.

Related