I am developing a C++ multi-threaded application and facing few issues related to member variable in multi thread program.
As far as I know heap for a each thread is common which is present in global area while each thread has its own stack. Please suggest how would member variable be shared in below cases:
Class of which object is made is Singleton and memory allocation is dynamic. Object is member variable.
Code sample:
class A
{
// SomeRandomClass is Singleton class
SomeRandomClass* someRandomClass::m_pInstance = NULL;
main()
{
pthread_t thread1;
pthread_create(&thread1,NULL,func,NULL)
}
func()
{
// Dynamic allocation and object is of singleton class
myObject = SomeRandomClass::instance();
}
}
Class of which object is made is regular class and memory allocation is dynamic. Object is member variable.
Code sample:
class A
{
// SomeRandom Class is not singleton
SomeRandomClass* m_pInstance = NULL;
main()
{
pthread_t thread1;
pthread_create(&thread1,NULL,func,NULL)
}
func()
{
// Dynamic allocation and object is of singleton class
myObject = new SomeRandomClass();
}
}
Class of which object is made is Singleton and memory allocation is static. Object is member variable.
Class of which object is made is regular class and memory allocation is static. Object is member variable.
Please help here as I read various articles online and I am not able to get the concept.
Whenever more than one thread accesses a variable, it requires some kind of synchronization so, for instance, multiple threads don't write to the variable at once.
For a singleton, synchronization is required for when the class is actually constructed (and this will differ depend on how it is implemented). It will also require synchronization when accessing the member variable of the class.
If this class is not used outside the thread that created it, then it requires no synchronization.
As mentioned, it's not clear to me what you mean by memory allocation is static.
Related
I have a threaded pipe-and-filter implementation where I want to use thread-local copies in one of my filters. I do not implement a run loop myself. Instead, the base Filter class calls a process() method on each of the filters whenever it gets data to be processed.
I have two issues with using thread_locals in this scenario:
1) I cannot declare thread_locals within the process() method, because the point is to reuse the thread locals whenever the process() method is called.
Example code below:
void process(SomeInput in) {
thread_local SomeClass* someClass = nullptr;
if (someClass == nullptr) someClass = new SomeClass(params);
// do stuff here...
}
So above I initialize a thread_local instance of SomeClass. But I do not deallocate it, because process() will be called by the same thread's run loop whenever new data arrives. Obviously, it the classes will never get freed. Bad.
2) I've added a threadCleanup() method to the filter implementation which gets now called whenever a filter is stopped (and it's thread(s) are stopped). Though that would require to declare thread_local member variables like:
class SomeFilter : public Filter <...> {
// ...
private:
thread_local SomeClass* _someClass;
}
But that doesn't work with classes and throws:
"thread_local is only allowed on variable declarations"
What is the proper way to declare, allocate and deallocate thread-locals in such scenario?
Answering with fix for your original problem instead of the new one you created for yourself:
Just make the original code use std::unique_ptr. You can even one-line it, since thread_local implies static, so it will only be initialized once without needing to perform per call tests for nullptr:
void process(SomeInput in) {
thread_local std::unique_ptr<SomeClass> someClass(new SomeClass(params));
// do stuff here...
}
The first time any given thread calls process, the unique_ptr is initialized for that thread; when that thread exits, the unique_ptr is destroyed and the SomeClass instance for that thread is collected, because thread_local destructors are called on thread exit.
Mind you, if someClass is small, you could store it directly in thread_local storage instead of storing the unique_ptr there pointing to the heap, which would let you avoid unique_ptr entirely, since as noted, thread_local implies static and calls destructors on thread exit:
void process(SomeInput in) {
thread_local SomeClass someClass(params);
// do stuff here,
// using someClass. instead of someClass-> for member/method access,
// and &someClass where you used to use someClass if something needs a raw
// pointer (the raw pointer is definitely sticking around until thread
// exit after all)
}
Using the unique_ptr approach might still be advantageous (thread local storage can be limited/slow, so it may be worthwhile to store the rest of the class in normal heap memory).
The syntax you are looking for is static thread_local on a member variable:
class SomeFilter : public Filter <...> {
// ...
private:
static thread_local SomeClass* _someClass;
}
Rather than performing manual cleanup it would be better to encapsulate _someClass in a unique_ptr, since thread locals are destroyed on thread exit:
static thread_local std::unique_ptr<SomeClass> _someClass;
I have two managers (which are singletons):
A licenses manager, counting licences tokens when functionalities are used. The destructor of this release all the licences.
A Python manager, managing calls to Python from C++, it requires a specific license from the licences manager. The destructor calls the licences manager to finalize the license usage.
I suppose the order of destruction of the singleton is undefined. How can I avoid the mismatch at the destruction of the managers? Is it possible?
This is my typical implementation of a singleton:
class Manager : private boost::noncopyable
{
private:
struct singleton_deleter { void operator () (Manager* m) { delete m; } };
friend struct Manager::singleton_deleter;
private:
boost::mutex singleton_mutex;
boost::shared_ptr<Manager> singleton_instance;
public:
static Manager& instance()
{
if(!(bool)Manager::singleton_instance)
{
boost::mutex::scoped_lock lock(Manager::singleton_mutex);
if(!(bool)Manager::singleton_instance)
Manager::singleton_mutex.reset(new Manager, Manager::singleton_deleter());
}
return *Manager::singleton_instance;
}
private:
Manager() { this->lic = LicManager::instance().getLicense(); }
~Manager() { LicManager::instance().releaseLicense(this->lic); }
};
Note that since the destruction order of static objects in C++ is the reverse of their construction order, you can make the constructor of one singleton first construct the other singleton it depends on as a function-local static object. For example:
LicManager & LicManager::instance() {
static LicManager licenceManager;
return licenceManager;
}
Manager & Manager::instance() {
static Manager manager(LicManager::instance());
return manager;
}
Another way would be to use a shared_ptr to share ownership of the singleton, enforcing the destruction order. Make instance() return a shared_ptr instead of a reference. In your use case, store the return value of LicManager::instance() (e.g. a shared_ptr<LicManager>) in your Manager object. This forces LicManager to stay alive for the lifetime of Manager, even if the respective LicManager shared pointer in the global scope is destroyed.
Edit: As pointed out in the comments, yet another solution would be to have only one super singleton which owns all the others and controls the initialization/destruction order.
Store the singleton instance as a static local variable of the accessor function that returns a reference to it. In other words, use the Construct On First Use Idiom.
Then call the accessor function of singleton A, from the constructor of singleton B. This ensures that, the singleton A is constructed before B, which in turn ensures that A is destroyed after B.
There is a variation of this pattern which is to use - instead of a function local static object - a function local static raw pointer to a dynamic object, which is leaked on termination. That approach does not need the constructor of a singleton to call the accessor of another, but of course memory analysers will complain. The idea is that that the singleton is never destroyed, so you are free to depend on it in the destructors of other static objects.
Is it really a so restrictive pattern than you can not have two different classes implemented as singletons ??? If it's true, singleton looks like a useless pattern...
Singleton is a very restrictive pattern, and some might argue that it is useless. But it is not true that you couldn't have two different singleton classes.
Assuming this implementation of a singleton pattern ( of course we should avoid Singleton: it is just question), I have just been thinking about static object being created. It is created on heap by a new operator, sure, but how is this destroyed? In following example we have a leak, so how one should implement deletion of static singleton object? Should there be a please_delete() public interface adopted, so one can call myC->please_delete() or is there other way to achieve this?
class CC{
public:
static CC* cObj(){
if(c_ptr==NULL){
c_ptr=new CC();
return c_ptr;
}else return c_ptr;
}
int getValue(){return value_;}
void setValue(int val){value_=val;}
~CC(){cout<<"~CC";}
private:
CC():value_(12345){cout<<"CC";}
static CC* c_ptr;
int value_;
};
// Allocating and initializing CC's
// static data member. The pointer is being
// allocated - not the object itself.
CC *CC::c_ptr = 0;
int main(){
//Singleton pattern
CC* myC = CC::cObj();
cout<<myC->getValue();
return 0;
}
output: CC12345
RUN SUCCESSFUL (total time: 67ms)
I noticed that indeed we can always declare singleton static instance within shared_ptr as with boost::shared_ptr<CC> bCptr(CC::cObj()); but Singleton pattern doesn't mention the problem of deletion of the object at all so maybe there exists some other approach?
Part of the Singleton design pattern is that it is indestructible.
EDIT:
There are 2 varieties of singletons with respect to destructibility:
Destructible (They die when the application does)
Indestructible (They die when the machine does)
Either way, if built properly, once the singleton instance is created, it stays. This one of the major criticisms of the Singleton design pattern.
Here are a few references that address the destructibility aspect of the pattern.
http://nicolabonelli.wordpress.com/2009/06/04/singleton-a-mirage-of-perfection/
http://www10.informatik.uni-erlangen.de/Teaching/Courses/SS2009/CPP/altmann.pdf
http://sourcemaking.com/design_patterns/singleton
http://sourcemaking.com/design_patterns/to_kill_a_singleton
The classical singleton pattern does not describe the deletion aspect.
However, if I have to do it, I would start with a simple approach like the following (it is not fool-proof):
1) Similar to the static method for creating/retrieving the singleton object, say createObject(), there is a static method for destructing the singleton object, say destructObject()
2) There is a counter which counts the current number of objects in the system;
it starts at 0
on createObject() call, it increments by 1
on deleteObject() call, it decrements by 1.
If it reaches 0, then the delete is called to actually destruct the object
I prefer to not use a pointer.
class Single
{
private:
Single();
public:
Single& Instance()
{
static Single the_instance;
Return the_instance;
}
};
This singleton will live from the time Instance() is called until the application is exiting and performing the destruction of static objects. In this case the destructor of the singleton object will be called.
In practice, even when using a pointer as in the original example, the memory will be reclaimed by the OS upon application exit. However in this case the object's destructor will not be called.
I know Java but don't have much knowledge of C++. I am trying to write a class for the first 3 statements in main function of the code at https://developers.google.com/v8/get_started.
First I have questions about how objects are created in C++. See the below code.
HandleScope handle_scope;
Persistent<Context> context = Context::New();
Context::Scope context_scope(context);
I think in C++ when you declare a variable of a class an instance of the class created at the point. You do not need to use new keyword like in Java. So the first statement would create an instance of HandleScope which will be stored in handle_scope.
Now I do not understand how the second statement would work. With my knowledge the part before = will create a new Persistent object which can be referred by the variable context. Then Context::New() will create a new object and store it in context? Huh, I know I am wrong. But I simply dont get how it would work?
I am trying to write a C++ class for the above. Here is my attempt.
class MyClass {
private:
HandleScope handle_scope;
Persistent<Context> context;
Context::Scope context_scope;
public:
MyClass();
};
MyClass::MyClass()
{
context = Context::New();
context_scope = new Context::Scope(context);
}
Have I done the initialization properly?
EDIT: Reply to peachykeen (in comments)
I did the following experimentation.
I wrote a Test class as below.
Test
{
public:
Test() {
cout << "Test" << endl;
}
};
In the main function I wrote Test test; It outputs "Test" which means an object is created without using new keyword.
You are right, in C++, objects are created as soon as they're defined. You do not need to use the new keyword.
However, unlike in Java, objects can be created with different kinds of duration. Using new creates an object on the heap, with dynamic storage duration: the variable lives until you explicitly delete it. (And new returns a pointer to the created object, so that you can track it)
If you simply define an object, as in your first and third lines, then it is created with automatic storage duration: that is, the object exists until it goes out of scope.
This means that you can create objects inside a function, and be guaranteed that they'll be destroyed as soon as you leave the function -- regardless of how you leave the function. Whether you return, or throw an exception, all objects with automatic storage duration (created without using new) are guaranteed to be properly cleaned up.
This means that you should always avoid new whenever possible. If you have to use new, you should typically wrap the resulting pointer into a smart pointer class, an object created with automatic storage duration, so that it gets destroyed automatically). The smart pointer will then call delete on the new-allocated object automatically, ensuring, again, that you don't leak memory.
This distinction is a very powerful tool, which good C++ programmers need to understand well. It is a key to avoiding memory leaks, or more generally, resource leaks of all kinds, and it is, in some respects, more powerful than Java's garbage collector.
For example, say we wish to open a file, and then write some data to it. In C++, we can do it like this:
void foo() {
std::ofstream file("foo.txt");
doStuff(file); // call a function which does something with the file
}
And because file was declared without using new, because it has automatic storage duration, we are guaranteed that it will have its destructor invoked when it goes out of scope, and it will be properly cleaned up -- that is, the stream will be flushed, and the file handle will be closed.
It doesn't matter if doStuff might throw an exception. No matter how we leave foo, file will be properly destroyed, so we don't need to mess about with try/finally like you would in Java. The class is exception-safe by itself, without requiring any additional effort from the user.
Try writing a similar snippet in Java, one which guarantees that even if doStuff throws an exception, the file will be immediately closed. It'll be much longer, and requires more care on the part of the user.
Persistent<Context> context = Context::New();
create object of type Persistent<Context>, initialized from returned of Context::New, if c-tor is not explicit.
Simple example.
#include <iostream>
class C
{
public:
C(int)
{
std::cout << "C::C(int)" << std::endl;
}
};
int main()
{
C c = 1;
}
your class should be
class MyClass {
private:
HandleScope handle_scope;
Persistent<Context> context;
Context::Scope context_scope;
public:
MyClass();
};
MyClass::MyClass():context(Context::New()),
context_scope(Context::Scope(context))
{
}
if Context::Scope is not pointer.
This would be the equivalent class:
class MyClass {
private:
HandleScope handle_scope;
Persistent<Context> context;
Context::Scope context_scope;
public:
MyClass();
};
MyClass::MyClass()
: context(Context::New()),
context_scope(context)
{
}
When you write a statement like this:
Persistent<Context> context = Context::New();
You are constructing context using the copy constructor. This is different from creating the object and then assigning a new value, although the result might often be equivalent.
Likewise this statement:
Context::Scope context_scope(context);
is constructing context_scope and passing context to the constructor. You get the equivalent behavior in a class using the constructor initializer syntax as in my example.
To create an instance of an object, you need only this: Type name; The newkeyword creates a pointer to an object. Normally, to initialize the object, we use parenthesis: Type name(parameter); Sometimes, when an object supports copying, you can use a function that returns an object and assign it to that object: Type name = Some_function_that_returns_Type(); You can now use name like any other object. If you say Type name = new Type;, you will get a compiler error. The keyword new returns a pointer. It would be correct to say Type * name = new Type;. (Note the *, saying that it is a pointer to a Type class, named name. When I refer to Type it is any object, such as your HandleScope. When I refer to name, it is the new object you are creating. The all of all is this: new is a completely different keyword that refers to pointers. If you are not using pointers, don't use it. Use the basic format Type name(parameter, another_param);.
I'm programming a game engine right now. The hardest part for me has been the memory management. I've been putting in as many optimizations as possible (because every frame counts, right?) and realized that the best way to approach this would be to do resource management using Stack and Pool allocators. The problem is, I can't figure out how to make a singleton class that is memory managed by these allocators.
My singletons are managers, so they are actually rather big, and memory management of them is important for the start up speed of my game. I basically want to be able to call my allocators' alloc() functions, which return type void*, and create my singleton in this allocated space.
I've been thinking about putting a static boolean called instantiated in each singleton class and having the constructor return NULL if instantiated is true. Would this work?
This is why everybody thinks Singletons suck. They suck horrifically. This is but one aspect of their suck, which will suck down your whole application with it.
In order to solve your problem: Do not use Suckletons.
Ok so I will answer this by sharing my own experience. Normally I want a class to have all its own functionality and later realize ok this might need a factory method to supply other code with an instance of my object that is singular. The instance really should only be defined once to maintain state etc. Therefore this is what I do for classes that don't have all of their initialization wrapped into construction. I don't want to clutter my existing class with singletonsuxness so I create a factory wrapper class to help me with this. You could use Myer's singleton pattern which is elegant and encapsulates the locking by letting the implementation of the static local variable (relies on compiler implementation of static local init which is not always a good idea) handle the locking but the problem comes if you, like me, want your objects default constructed so that you can use STL vectors etc on them easily and later call some type of initialization on them, possibly passing parameters to this method, to make them heavier.
class X
{
public:
bool isInitialized () { return _isInitialized; } ; // or some method like
// establishCxn to have it
// bootstrapped
void initialize();
X() {} // constructor default, not initialized, light weight object
private:
bool _isInitialzied;
};
// set initialization to false
X::X(): _isInitialized(false) {}
void X::intialize()
{
if (isInitiazlied()) { return; }
.... init code ....
_isInitialized = true
}
// now we go ahead and put a factory wrapper on top of this to help manage the
// singletoness nature. This could be templatized but we don't as we want the
// flexibility to override our own getinstance to call a specific initialize for the
// object it is holding
class XFactory
{
public:
static X* getInstance();
private:
static boost::mutex _lock;
// light weight static object of yourself ( early instantiation ) to put on the stack
// to avoid thread issues, static method member thread saftey, and DCLP pattern
// threading races that can stem from compiling re-ordering of items
static XFactory _instance;
// making this pointer volatile so that the compiler knows not to reorder our
// instructions for it ( depends on compiler implementation but it is a safe guard )
X* volatile _Xitem;
X* getXitem () { return _Xitem; }
void createInstance();
void doCleanUp();
// stop instantiation or unwanted copies
XClientFactory();
~XClientFactory();
XClientFactory(XClientFactory const&);
XClientFactory& operator=(XClientFactory const&);
};
// on construction we create and set the pointer to a new light weight version of the
// object we are interested in construction
XFactory::XFactory() : _Xitem( new X; )
{
}
// note our factory method is returning a pointer to X not itself (XFactory)
X* XFactory::getInstance()
{
// DCLP pattern, first thread might have initialized X while others
// were waiting for the lock in this way your double check locking is
// on initializing the X container in the factory and not the factory object itself.
// Worst case your initialization could happen more than once but it should check the
// boolean before it starts (see initialization method above) and sets the boolean at
// the end of it. Also your init should be such that a re-initialization will not put
// the object in a bad state. The most important thing to note is that we
// moved the double check locking to the contained object's initialization method
// instead of the factory object
if (! XFactory::_instance.getXitem()->isInitialized() )
{
boost::unique_lock<boost::mutex> guard(XFactory::_lock);
if (! XFactory::_instance.getXitem()->isInitialized() )
{
XFactory::_instance.getXitem()->initialize();
}
}
return XFactory::_instance.getXitem();
}
// XFactory private static instance on the stack will get cleaned up and we need to
// call the delete on the pointer we created for the _Xitem
XFactory::~XFactory()
{
doCleanUp();
}
XFactory::doCleanUp()
{
delete _Xitem; //
}
That's it, let me know what you think. I also wrestled recently with singleton and all the pit falls. Also, we are not using a 0x compiler yet that would ensure that the Myers singleton will be implemented in a thread safe way just using a local static variable