Skip to content

Instantly share code, notes, and snippets.

@icecoobe
Last active December 14, 2023 10:18
Show Gist options
  • Save icecoobe/4de400ba7f6452fada5533a01888737d to your computer and use it in GitHub Desktop.
Save icecoobe/4de400ba7f6452fada5533a01888737d to your computer and use it in GitHub Desktop.
#include <iostream>
#include <mutex>
#include <thread>
namespace
{
std::once_flag init_once_flag;
}
class singleton
{
public:
static singleton* instance()
{
std::call_once(init_once_flag, init);
return instance_;
}
void print_something()
{
std::cout << __FUNCTION__ << ": hello" << std::endl;
}
private:
singleton() = default;
~singleton() = default;
static void init()
{
std::cout << "[init]" << std::endl;
if (instance_ == nullptr)
{
instance_ = new singleton();
}
}
private:
static singleton *instance_;
};
singleton* singleton::instance_ = nullptr;
int main()
{
// singleton::instance()->print_something();
// singleton::instance()->print_something();
// singleton::instance()->print_something();
// singleton::instance()->print_something();
std::thread t([](){
std::cout << "- 1" << std::endl;
singleton::instance()->print_something();
std::cout << "=====" << std::endl;
});
std::thread t2([](){
std::cout << "- 2" << std::endl;
singleton::instance()->print_something();
std::cout << "=====" << std::endl;
});
std::thread t3([](){
std::cout << "- 3" << std::endl;
singleton::instance()->print_something();
std::cout << "=====" << std::endl;
});
t.join();
t2.join();
t3.join();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment