flatten 20260225
This commit is contained in:
112
tjp/core/singleton/ThreadSafeSingleton.hpp
Executable file
112
tjp/core/singleton/ThreadSafeSingleton.hpp
Executable file
@@ -0,0 +1,112 @@
|
||||
// TJP COPYRIGHT HEADER
|
||||
|
||||
/**
|
||||
* legal header
|
||||
*
|
||||
* ============================================================================
|
||||
* TJP 10/11/01 Got rid of the constructed singleton, it was essentially
|
||||
* a pointer!
|
||||
*
|
||||
* @author Timothy Prepscius
|
||||
* @created 3/../01
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "ThreadSafeSingleton.h"
|
||||
#include "../threads/Monitor.h"
|
||||
|
||||
namespace timprepscius {
|
||||
namespace core {
|
||||
|
||||
/**
|
||||
* a Singleton container, whose contained instance is constructed on its
|
||||
* first request
|
||||
*
|
||||
* T defines the class pointer type
|
||||
* X defines the allocation class type
|
||||
*/
|
||||
|
||||
template<class T>
|
||||
class ThreadSafeSingletonNoConstruct : public Monitor<T>
|
||||
{
|
||||
public:
|
||||
typedef Monitor<T> Super;
|
||||
typedef typename Super::Writer Accessor;
|
||||
|
||||
protected:
|
||||
// only called by reader/writer after lock
|
||||
virtual T *access() const
|
||||
{
|
||||
return this->object;
|
||||
}
|
||||
|
||||
public:
|
||||
ThreadSafeSingletonNoConstruct () :
|
||||
Super(NULL)
|
||||
{
|
||||
}
|
||||
|
||||
virtual ~ThreadSafeSingletonNoConstruct()
|
||||
{
|
||||
deleteInstance();
|
||||
}
|
||||
|
||||
virtual void setInstance (T *instance)
|
||||
{
|
||||
Accessor w(*this);
|
||||
{
|
||||
this->object = instance;
|
||||
}
|
||||
}
|
||||
|
||||
void deleteInstance()
|
||||
{
|
||||
Accessor w(*this);
|
||||
|
||||
if (this->object)
|
||||
delete this->object;
|
||||
|
||||
this->object = NULL;
|
||||
}
|
||||
} ;
|
||||
|
||||
template<class T, class X=T>
|
||||
class ThreadSafeSingleton : public ThreadSafeSingletonNoConstruct<T>
|
||||
{
|
||||
public:
|
||||
typedef ThreadSafeSingletonNoConstruct<T> Super;
|
||||
typedef typename Super::Writer Accessor;
|
||||
|
||||
protected:
|
||||
// only called by reader/writer after lock
|
||||
virtual T *access() const
|
||||
{
|
||||
if (!this->object)
|
||||
{
|
||||
const_cast<ThreadSafeSingleton<T> *>(this)->setInstance(new T());
|
||||
}
|
||||
|
||||
return this->object;
|
||||
}
|
||||
|
||||
public:
|
||||
virtual ~ThreadSafeSingleton()
|
||||
{
|
||||
Super::deleteInstance();
|
||||
}
|
||||
|
||||
virtual void setInstance (T *instance)
|
||||
{
|
||||
Accessor a(*this);
|
||||
|
||||
if (this->object)
|
||||
delete this->object;
|
||||
|
||||
this->object = instance;
|
||||
}
|
||||
} ;
|
||||
|
||||
} // namespace utilities
|
||||
} // namespace
|
||||
|
||||
Reference in New Issue
Block a user