vendredi 23 septembre 2022

How to write a thread-save singliton using C++11

I'm not sure does this is thread-safe:

#include <thread>
#include <stdio.h>

class A {
public:
  static A* instance() {
      static A* ptr = new A();
      return ptr;
  }

  int val_;
};

int main(int argc, char *argv[]) {
  auto ptr = A::instance();
  printf("thread value: %d\n", ptr->val_);
  //thd1.join();
  return 0;
}

The C++ code and ARM assembly: https://godbolt.org/z/aPYarcoM9

I've understand that the guard variable ensure the static variable initialized once only, and the guard aquire/release lock the construction of class A.

What I not sure is the following is thread-safe?

auto ptr = A::instance();

Aucun commentaire:

Enregistrer un commentaire