I'm trying to create a multi threaded and templated singleton as part of my advance c++ study. I've been told I have a race condition in my code and after hours of trying to figure it out i can't find it.
I won't write the whole class (though it's a simple one) but the exact location where I've been focused down to:
template <class T>
void Singleton<T>::onceFunction()
{
static T instanceObject;
Singleton<T>::instance = &instanceObject;
}
template <class T>
T& Singleton<T>::getInstance()
{
while (0 == Singleton::instance)
{
static pthread_once_t once_control = PTHREAD_ONCE_INIT;
pthread_once(&once_control, Singleton<T>::onceFunction);
}
return *Singleton::instance;
}
I'm using pthread_once() since I'm not compiling with c++11.