CodexBloom - Programming Q&A Platform

How to properly implement a thread-safe singleton in C++11 using std::call_once?

👀 Views: 91 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-03
c++11 singleton multithreading C++

I've searched everywhere and can't find a clear answer... I'm maintaining legacy code that This might be a silly question, but Hey everyone, I'm running into an issue that's driving me crazy. I'm trying to implement a thread-safe singleton pattern in C++11, and I want to use `std::call_once` for initialization. However, I'm running into issues with the order of initialization and thread safety. Here's what I have so far: ```cpp #include <iostream> #include <mutex> #include <memory> class Singleton { public: static Singleton& getInstance() { std::call_once(initInstanceFlag, &Singleton::initSingleton); return *instance; } void doSomething() { std::cout << "Doing something!" << std::endl; } private: Singleton() {} // Private constructor ~Singleton() {} Singleton(const Singleton&) = delete; // Prevent copy Singleton& operator=(const Singleton&) = delete; // Prevent assignment static void initSingleton() { instance.reset(new Singleton()); } static std::unique_ptr<Singleton> instance; static std::once_flag initInstanceFlag; }; std::unique_ptr<Singleton> Singleton::instance; std::once_flag Singleton::initInstanceFlag; ``` I've read that `std::call_once` should ensure only one initialization of `instance`, but when I run the following code: ```cpp #include <thread> void threadFunction() { Singleton::getInstance().doSomething(); } int main() { std::thread t1(threadFunction); std::thread t2(threadFunction); t1.join(); t2.join(); return 0; } ``` I occasionally get crashes or undefined behavior, particularly when the threads are executed simultaneously. I suspect there might be something wrong with how `instance` is being initialized or accessed. Am I missing something in my implementation of the singleton pattern? Is there a better approach to ensure thread safety in C++11 without running into these issues? My development environment is Ubuntu. Any ideas what could be causing this? For context: I'm using C++ on macOS. The stack includes C++ and several other technologies. This is part of a larger web app I'm building. I'd really appreciate any guidance on this. Am I approaching this the right way? I'm open to any suggestions.