Callback into singleton class - c++

I am using a singleton class with a thread that calls into the singleton. I was asked during a review why I used the this pointer instead of the singleton instance.
My code with the suggested changes.
class myClass : public threadWrapper
{
public:
static myClass& instance()
{
static myClass instance;
return instance;
}
// This is the callback that I have implemented
static void callback(void *me)
{
if (me != NULL)
static_cast<myClass*>(me)->doCallback();
}
// This is the suggested callback
static void callback2(void *me)
{
instance().doCallback();
}
// caller gets instance and then calls initialise()
int initialise()
{
if (initialised)
return ERROR_ALREADY_INITIALISED;
// Initialise the class
// my thread startup call
// thread wrapper class initialisation that calls pthread_create that runs the callback method with this as a parameter
// priority is a global value that difines the relative priority of the various threads.
threadWrapper::Initialise(priority, callback, this);
initialised = true;
}
private:
myClass() : initialised(false) {;}
void doCallback(void);
bool initialised;
static const int
}
So is there any significant difference in speed between the two?
The threadWrapper is mandated in the existing code base, and I'm not allowed to use boost.
My justification was that if we needed to make this not a singleton then fewer changes would be required.

The speed difference will be pretty much nonexistent.
As for code quality, Singletons are quite horrendous and I personally would chuck out both forms, especially in a threaded environment. Assuming that it's too late for that, however.
The thing is, if you're gonna pass in a pointer to the object, why not just not make that object global in the first place? And if you are, it should at least be strongly typed. And then, you're just ... wrapping a member method in a static method? Why bother? Anyone who has a pointer to the class can just call the method on it in the first place. This is just insane.
Edit: If you're stuck with the existing design, then the second version is definitely better than the first and no slower. Even if you have existing code that depends on the Singleton, then it's absolutely better to refactor what you can to not depend on it.

Related

A singleton-like manager class, better design?

I'm making a game engine and I'm using libraries for various tasks. For example, I use FreeType which needs to be initialized, get the manager and after I don't use it I have to de-initialize it. Of course, it can only be initialized once and can only be de-initialized if it has been initialized.
What I came up with (just an example, not "real" code [but could be valid C++ code]):
class FreeTypeManager
{
private:
FreeTypeManager() {} // Can't be instantiated
static bool initialized;
static TF_Module * module; // I know, I have to declare this in a separate .cpp file and I do
public:
static void Initialize()
{
if (initialized) return;
initialized = true;
FT_Initialize();
FT_CreateModule(module);
}
static void Deinitialize()
{
if (!initialized) return;
initialized = false;
FT_DestroyModule(module);
FT_Deinit();
}
};
And for every manager I create (FreeType, AudioManager, EngineCore, DisplayManager) it's pretty much the same: no instances, just static stuff. I can see this could be a bad design practice to rewrite this skeleton every time. Maybe there's a better solution.
Would it be good to use singletons instead? Or is there a pattern suiting for my problem?
If you still want the singleton approach (which kind of makes sense for manager-type objects), then why not make it a proper singleton, and have a static get function that, if needed, creates the manager object, and have the managers (private) constructor handle the initialization and handle the deinitialization in the destructor (though manager-type objects typically have a lifetime of the whole program, so the destructor will only be called on program exit).
Something like
class FreeTypeManager
{
public:
static FreeTypeManager& get()
{
static FreeTypeManager manager;
return manager;
}
// Other public functions needed by the manager, to load fonts etc.
// Of course non-static
~FreeTypeManager()
{
// Whatever cleanup is needed
}
private:
FreeTypeManager()
{
// Whatever initialization is needed
}
// Whatever private functions and variables are needed
};
If you don't want a singleton, and only have static function in the class, you might as well use a namespace instead. For variables, put them in an anonymous namespace in the implementation (source) file. Or use an opaque structure pointer for the data (a variant of the pimpl idiom).
There's another solution, which isn't exactly singleton pattern, but very related.
class FreeTypeManager
{
public:
FreeTypeManager();
~FreeTypeManager();
};
class SomeOtherClass
{
public:
SomeOtherClass(FreeTypeManager &m) : m(m) {}
private:
FreeTypeManager &m;
};
int main() {
FreeTypeManager m;
...
SomeOtherClass c(m);
}
The solution is to keep it ordinary c++ class, but then just instantiate it at the beginning of main(). This moves initialisation/destruction to a little different place. You'll want to pass references to FreeTypeManager to every class that wants to use it via constructor parameter.
Note that it is important that you use main() instead of some other function; otherwise you get scoping problems which require some thinking how to handle..

C++ static , extern uses with global data

I'm new to C++ and OOP in general and have been trying to learn efficient or 'correct' ways to do things, but am still having trouble.
I'm creating a DataStore class that holds data for other classes/objects. There will only ever be one instance/object of this class; however, there doesn't really need to be an object/instance since it's global data, right. In this case I feel like it's just a way to provide scope. So, I want to directly change the class members instead of passing around the object. I have read about static and _extern, but I can't decide if either would be viable, or if anything else would be better.
Right now I'm passing the one created object around to change it's data, but I would rather the class be accessed as 'itself' instead of by 'an instance of itself' while still retaining the idea of it being an object.
Typically, this sort of problem (where you need one, but only ever one - and you are SURE you never ever need more), is solved by using a "singleton" pattern.
class Singleton
{
public:
static Singleton* getInstance()
{
if (!instance) instance = new Singleton();
return instance;
}
int getStuff() { return stuff; }
private:
Singleton() { stuff = 42; }
static Singleton *instance;
int stuff;
};
then in some suitiable .cpp file>
static Singleton *instance;
Or use a global variable directly:
class Something
{
public:
Something() { stuff = 42; }
int getStuff() { return stuff; }
private:
int stuff;
}
extern Something global_something; // Make sure everyone can find it.
In ONE .cpp file:
Something global_something;
Since BOTH of these are essentially a global variable solution, I expect someone disliking global variables will downvote it, but if you don't want to pass around your class object everywhere, a global variable is not a terrible idea. You just have to be aware that global variables are not necessarily a great idea as a solution in general. It can be hard to follow what is going on, and it certainly gets messy if you suddenly need more than one (because you decided to change the code to support two different storages, or whatever) - but this applies to a singleton too.
EDIT: In a comment OP explained the data store will be read by code running in multiple threads, and updated by code in one thread. My previous answer no longer applies. Here's a better answer.
Don't use a global variable to hold the store's instance. This will open the door for many subtle bugs that can haunt you for a long while. You should give your reading threads read-only access to the store. Your writing thread should get read-write access.
Make sure your read methods in the data store are properly marked as const. Then create a single instance of the data store, and put a pointer to it in a const global variable. Your writing thread should have another mechanism of getting a non-const pointer (add a GetInstance public static method, as suggested by #Mats).
My previous answer:
If you're certain there will always be just one data store instance, don't pass it around.
Global variables are frowned upon, and some languages (Java and C#) outlawed them altogether. So in C# and Java you use static class members instead, which are practically the same thing (with exactly the same problems).
If you can put your single instance in a a const global variable, you should be fine.
If you're doing any kind of multithreading, you'll need to make sure your store is thread-safe, or else really bad things will happen.
I do this for object that have 1 instance most of time during execution of program.
class Object {
private:
Object();
friend Object & GetObject();
public:
...
};
inline Object & GetObject() {
static Object O;
return O;
}
1) this is less verbose than singleton.
2) this avoid pitfall of global object, such as undefined initialization order.
you can use a controversial Singleton pattern or you can use one of PARAMETERISE FROM ABOVE approaches described in Mark Radford (Overload Journal #57 – Oct 2003) SINGLETON - the anti-pattern! article.
PARAMETERISE FROM ABOVE approach (in his opinion) strengthen encapsulation and ease initialisation difficulties.
The classic lazy evaluated and correctly destroyed singleton:
class S
{
public:
static S& getInstance()
{
static S instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
S() {}; // Constructor? (the {} brackets) are needed here.
// Dont forget to declare these two. You want to make sure they
// are unaccessable otherwise you may accidently get copies of
// your singleton appearing.
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
};
But note: this is not thread-safe.
see here for good StackOverflow post about Singletons

Common pattern for library initialization and shutdown?

Is there a pattern that I may use for calling the required initialization and cleanup routines of an underlying (C) library? In my case, I would like to create the wrapper class so that it can be composed into other objects. The problem is that, when I destroy the wrapper class, the cleanup routines of the underlying library are called. That's fine until I instantiate multiple objects of my wrapper class. My question is what is the best way to really handle this situation? A static reference counter comes to mind, but I wanted to know if there were other potentially better options and the trades involved.
If the initialization can be called before main starts, and cleanup called after main ends, this little trick (hack?) might work for you:
#include <iostream>
// C library initialization routine
void init() {std::cout << "init\n";}
// C library cleanup routine
void fini() {std::cout << "fini\n";}
// Put this in only one of your *.cpp files
namespace // anonymous
{
struct Cleaner
{
Cleaner() {init();}
~Cleaner() {fini();}
};
Cleaner cleaner;
};
int main()
{
std::cout << "using library\n";
}
Output:
init
using library
fini
It uses (abuses?) the fact that constructors for static objects are called before main, and that destructors are called after main. It's like RAII for the whole program.
Not everything has to be a class. The Singleton pattern would let you turn this into a class, but it's really not buying you anything over global functions:
bool my_library_init();
void my_library_shutdown();
The first call returns true if the library was successfully initialized, the second just quietly does whatever needs to be done and exits. You can add whatever reference counting or thread tracking type stuff behind these interfaces you like.
Also, don't neglect the possibility that your library may be able to do all of this transparently. When the first library function is called, could it detect that it is not initialized yet and set everything up before doing the work? For shutdown, just register the resources to be destroyed with a global object, so they are destroyed when the program exits. Doing it this way is certainly trickier, but may be worth the usability benefit to your library's callers.
I have seen a lot of Singleton talk, so I can only recommend a look at Alexandrescu's work.
However I am not sure that you really need a Singleton there. Because if you do, you assume that all your calls are going to share the state... is it the case ? Do you really wish when you call the library through a different instance of Wrapper to get the state in which the last call set it ?
If not, you need to serialize the access, and reinitialize the data each time.
class Wrapper
{
public:
Wrapper() { lock(Mutex()); do_init_c_library(); }
~Wrapper() { do_clean_up_c_library(); unlock(Mutex()); }
private:
static Mutex& Mutex() { static Mutex MMutex; return MMutex; }
}; // class Wrapper
Quite simple... though you need to make sure that Mutex is initialized correctly (once) and live until it's not needed any longer.
Boost offers facilities for the once issue, and since we use a stack based approach with MMutex it should not go awry... I think (hum).
If you can change the library implementation, you could have each call to one of the library's functions access a singleton which is created on first use.
Or you put a global/static variable into the library which initializes it during construction and shuts it down during destruction. (That might become annoying if the library uses global variables itself and the order of initialization/shutdown conflicts with them. Also, linkers might decide to eliminate unreferenced globals...)
Otherwise, I don't see how you want to avoid reference counting. (Note, however, that it has the drawback of possibly creating multiple init/shutdown cycles during the program's lifetime.)
If your set of C library routines is not too large, you can try combining the Singleton and Facade patterns so that C library routines are only invoked via the Facade. The Facade ensures the initialization and cleanup of the C library. Singleton insures that there is only one instance of the Facade.
#include <iostream>
// C library initialization and cleanup routines
void init() {std::cout << "init\n";}
void fini() {std::cout << "fini\n";}
// C library routines
void foo() {std::cout << "foo\n";}
void bar() {std::cout << "bar\n";}
class Facade // Singleton
{
public:
void foo() {::foo();}
void bar() {::bar();}
static Facade& instance() {static Facade instance; return instance;}
private:
Facade() {init();}
~Facade() {fini();}
};
// Shorthand for Facade::instance()
inline Facade& facade() {return Facade::instance();}
int main()
{
facade().foo();
facade().bar();
}
Output:
init
foo
bar
fini

Global instance of a class in C++

As the title says. How would I create an instance of a class that is globally available(for example I have a functor for printing and i want to have a single global instance of this(though the possibility of creating more)).
Going to all the effort of making a singleton object using the usual pattern isn't addressing the second part of your question - the ability to make more if needed. The singleton "pattern" is very restrictive and isn't anything more than a global variable by another name.
// myclass.h
class MyClass {
public:
MyClass();
void foo();
// ...
};
extern MyClass g_MyClassInstance;
// myclass.cpp
MyClass g_MyClassInstance;
MyClass::MyClass()
{
// ...
}
Now, in any other module just include myclass.h and use g_MyClassInstance as usual. If you need to make more, there is a constructor ready for you to call.
First off the fact that you want global variables is a 'code smell' (as Per Martin Fowler).
But to achieve the affect you want you can use a variation of the Singleton.
Use static function variables. This means that variable is not created until used (this gives you lazy evaluation) and all the variables will be destroyed in the reverse order of creation (so this guarantees the destructor will be used).
class MyVar
{
public:
static MyVar& getGlobal1()
{
static MyVar global1;
return global1;
}
static MyVar& getGlobal2()
{
static MyVar global2;
return global2;
}
// .. etc
}
As a slight modification to the singleton pattern, if you do want to also allow for the possibility of creating more instances with different lifetimes, just make the ctors, dtor, and operator= public. That way you get the single global instance via GetInstance, but you can also declare other variables on the heap or the stack of the same type.
The basic idea is the singleton pattern, however.
Singleton is nice pattern to use but it has its own disadvantages. Do read following blogs by Miško Hevery before using singletons.
Singletons are Pathological Liars
Root Cause of Singletons
Where Have All the Singletons Gone?
the Singleton pattern is what you're looking for.
I prefer to allow a singleton but not enforce it so in never hide the constructors and destructors. That had already been said just giving my support.
My twist is that I don't use often use a static member function unless I want to create a true singleton and hide the constr. My usual approach is this:
template< typename T >
T& singleton( void )
{
static char buffer[sizeof(T)];
static T* single = new(buffer)T;
return *single;
}
Foo& instance = singleton<Foo>();
Why not use a static instance of T instead of a placement new? The static instance gives the construction order guarantees, but not destruction order. Most objects are destroyed in reverse order of construction, but static and global variables. If you use the static instance version you'll eventually get mysterious/intermittent segfaults etc after the end of main.
This means the the singletons destructor will never be called. However, the process in coming down anyway and the resources will be reclaimed. That's kinda tough one to get used to but trust me there is not a better cross platform solution at the moment. Luckily, C++0x has a made changes to guarantee destruction order that will fix this problem. Once your compiler supports the new standard just upgrade the singleton function to use a static instance.
Also, I in the actual implemenation I use boost to get aligned memory instead of a plain character array, but didn't want complicate the example
The simplest and concurrency safe implementation is Scott Meyer's singleton:
#include <iostream>
class MySingleton {
public:
static MySingleton& Instance() {
static MySingleton singleton;
return singleton;
}
void HelloWorld() { std::cout << "Hello World!\n"; }
};
int main() {
MySingleton::Instance().HelloWorld();
}
See topic IV here for an analysis from John Vlissides (from GoF fame).

Best way to start a thread as a member of a C++ class?

I'm wondering the best way to start a pthread that is a member of a C++ class? My own approach follows as an answer...
This can be simply done by using the boost library, like this:
#include <boost/thread.hpp>
// define class to model or control a particular kind of widget
class cWidget
{
public:
void Run();
}
// construct an instance of the widget modeller or controller
cWidget theWidget;
// start new thread by invoking method run on theWidget instance
boost::thread* pThread = new boost::thread(
&cWidget::Run, // pointer to member function to execute in thread
&theWidget); // pointer to instance of class
Notes:
This uses an ordinary class member function. There is no need to add extra, static members which confuse your class interface
Just include boost/thread.hpp in the source file where you start the thread. If you are just starting with boost, all the rest of that large and intimidating package can be ignored.
In C++11 you can do the same but without boost
// define class to model or control a particular kind of widget
class cWidget
{
public:
void Run();
}
// construct an instance of the widget modeller or controller
cWidget theWidget;
// start new thread by invoking method run on theWidget instance
std::thread * pThread = new std::thread(
&cWidget::Run, // pointer to member function to execute in thread
&theWidget); // pointer to instance of class
I usually use a static member function of the class, and use a pointer to the class as the void * parameter. That function can then either perform thread processing, or call another non-static member function with the class reference. That function can then reference all class members without awkward syntax.
You have to bootstrap it using the void* parameter:
class A
{
static void* StaticThreadProc(void *arg)
{
return reinterpret_cast<A*>(arg)->ThreadProc();
}
void* ThreadProc(void)
{
// do stuff
}
};
...
pthread_t theThread;
pthread_create(&theThread, NULL, &A::StaticThreadProc, this);
I have used three of the methods outlined above.
When I first used threading in c++ I used static member functions, then friend functions and finally the BOOST libraries. Currently I prefer BOOST. Over the past several years I've become quite the BOOST bigot.
BOOST is to C++ as CPAN is to Perl. :)
The boost library provides a copy mechanism, which helps to transfer object information
to the new thread. In the other boost example boost::bind will be copied with a pointer, which is also just copied. So you'll have to take care for the validity of your object to prevent a dangling pointer. If you implement the operator() and provide a copy constructor instead and pass the object directly, you don't have to care about it.
A much nicer solution, which prevents a lot of trouble:
#include <boost/thread.hpp>
class MyClass {
public:
MyClass(int i);
MyClass(const MyClass& myClass); // Copy-Constructor
void operator()() const; // entry point for the new thread
virtual void doSomething(); // Now you can use virtual functions
private:
int i; // and also fields very easily
};
MyClass clazz(1);
// Passing the object directly will create a copy internally
// Now you don't have to worry about the validity of the clazz object above
// after starting the other thread
// The operator() will be executed for the new thread.
boost::thread thread(clazz); // create the object on the stack
The other boost example creates the thread object on the heap, although there is no sense to do it.