Skip to content

Instantly share code, notes, and snippets.

@christiankakesa
Created January 10, 2011 23:16
Show Gist options
  • Save christiankakesa/773682 to your computer and use it in GitHub Desktop.
Save christiankakesa/773682 to your computer and use it in GitHub Desktop.
Singleton template
// Singleton threadsafe sample
// by Christian Kakesa <[email protected]>
// (c) 2011
#include "exemple.h"
int Exemple::get_number() const
{
return number_;
}
void Exemple::set_number(const int n)
{
number_ = n;
}
// Singleton threadsafe sample
// by Christian Kakesa <[email protected]>
// (c) 2011
#ifndef __EXEMPLE_H_
#define __EXEMPLE_H_
#include "singleton.h"
class Exemple : public Singleton<Exemple>
{
public:
int get_number() const;
void set_number(const int n);
private:
int number_;
};
#endif//!__EXEMPLE_H_
// Singleton threadsafe sample
// by Christian Kakesa <[email protected]>
// (c) 2011
#include "exemple.h"
#include "singleton.h"
#include <iostream>
int main(int ac, char **av)
{
Singleton<Exemple>::instance().set_number(10);
std::cout << "set_number(10): " << Singleton<Exemple>::instance().get_number() << std::endl;
Singleton<Exemple>::instance().set_number(15);
std::cout << "set_number(15): " << Singleton<Exemple>::instance().get_number() << std::endl;
Singleton<Exemple>::instance().set_number(20);
std::cout << "set_number(20): " << Singleton<Exemple>::instance().get_number() << std::endl;
return 0;
}
// Singleton threadsafe old style sample
// by Christian Kakesa <[email protected]>
// (c) 2011
#ifndef __SINGLETON_H_
#define __SINGLETON_H_
#include <cstdlib> //std::atexit()
#define MFENCE "memory_fence"
#define MUTEX_LOCK "lock"
#define MUTEX_UNLOCK "unlock"
#define MEMORY_READWRITE_BARRIER "memory_barrier"
template <typename T>
class Singleton
{
public:
static T& instance()
{
return *get_instance();
}
static const T& const_instance()
{
return *get_instance();
}
static void destroy()
{
MFENCE; //On s'assure que tous les caches processeurs sont à niveau
if (pInstance_ != 0)
delete pInstance_;
}
protected:
Singleton(){}
~Singleton()
{
pInstance_ = 0;
created_ = false;
}
private:
static T* pInstance_;
static volatile bool created_;
Singleton(const Singleton &);
Singleton& operator= (const Singleton &);
static T* get_instance()
{
if (created_ == false)
{
MUTEX_LOCK; //On s'assure qu'un seul thread a la main
if (pInstance_ == 0)
{
pInstance_ = new T();
std::atexit(Singleton::destroy);
}
MUTEX_UNLOCK;
MEMORY_READWRITE_BARRIER; //On s'assure que le compilateur ne change pas l'ordre de ces 2 instructions
created_ = true;
MFENCE; //On s'assure que tous les caches processeurs sont à niveau
}
return pInstance_;
}
};
template<typename T> T* Singleton<T>::pInstance_ = 0;
template<typename T> volatile bool Singleton<T>::created_ = false;
#endif//!__SINGLETON_H_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment