Created
December 29, 2014 17:15
-
-
Save dgodfrey206/a175656ef1439ff4196b to your computer and use it in GitHub Desktop.
Thread-safe singleton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
p1
andp2
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.