March 26th, 2013, 01:54 PM
Singleton vs Globals vs Alternatives (Best Practice, Design)
I'm trying to determine the best way of implementing a few things, but the key one is an 'application quitting' method. While this applies to many different projects in different ways, let me explain a good, real-world example:
A thread is spawned that is tasked with processing data passed in from other threads; it is signalled when there is work to do:
Since this thread is blocking, when the user wants the application to quit, it will be torn down dramatically (or at least, not in the method we desire, so it can properly clean up) - hence we signal the thread so it executes, where it then checks the global variable to see if the signal was a result of application closure.
for ( ;; )
if ( g_quitting )
// do work
If it is, it breaks out of the loop, does its cleanup, and returns in short order. Consider I have 2-8 of these threads (but potentially many more).
Is this one of those rare cases that a global variable is tentatively allowed?
I've also considered using a singleton to maintain this, which has a method to access this; while it has the benefit that only a friend class can 'set' the quitting state, as far as I'm aware it's nothing more than a glorified global, with its own set of drawbacks:
I use a similar method for maintaining multiple connections to servers, which block on a read from the socket.
What method would YOU use to perform such a case? There must be other applications out there with similar operations, but I want to use good practice, and wonder if there is a different way these can be designed?
Click Here to Expand Forum to Full Width
This a Codeguru.com survey!