Tag: C++, singleton, multithreading

  • Implementing a Thread-Safe Singleton in C++

    A singleton ensures a class has only one instance. In multithreaded applications, making it thread-safe is crucial. Using mutexes helps synchronize access to the singleton instance. Here’s how you can implement it:

    “`cpp
    #include
    #include
    using namespace std;
    class Singleton {
    public:
    static Singleton& getInstance() {
    static Singleton instance;
    return instance;
    }
    private:
    Singleton() {} // Private constructor
    };
    int main() {
    Singleton& s1 = Singleton::getInstance();
    return 0;
    }
    “`

    In this code, `getInstance` returns the singleton instance. This ensures only one instance is created safely. Thread safety is essential in concurrent programming.