Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Created December 29, 2014 17:15
Show Gist options
  • Save dgodfrey206/a175656ef1439ff4196b to your computer and use it in GitHub Desktop.
Save dgodfrey206/a175656ef1439ff4196b to your computer and use it in GitHub Desktop.
Thread-safe singleton
#include <mutex>
#include <thread>
#include <iostream>
struct Singleton
{
static Singleton& instance()
{
std::lock_guard<std::mutex> lock(m);
static Singleton s;
return s;
}
Singleton() = default;
Singleton(Singleton const&) = delete;
Singleton& operator=(Singleton const&) = delete;
private:
static std::mutex m;
};
std::mutex Singleton::m;
int main()
{
Singleton *p1, *p2;
std::thread t1([&] { p1 = &Singleton::instance(); });
std::thread t2([&] { p2 = &Singleton::instance(); });
t1.join();
t2.join();
std::cout << p1 << " " << p2;
}
@dgodfrey206
Copy link
Author

p1 and p2 point to the same singleton. Had a mutex not been used, the initialization of the static singleton object couldn't been accessed concurrently leading to the creation of two different singleton objects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment