Automatically Call Method After Final Constructor - c++

I have written up a framework for threaded objects with the following very basic structure:
class ThreadedObject {
public:
ThreadedObject(Thread* parentThread);
protected:
virtual void initialize();
}
class MyThreadedObject {
public:
MyThreadedObject(Thread* parentThread) : ThreadedObject(parentThread) {}
protected:
void initialize() override;
}
I have a mechanism whereby I don't call methods of subclasses of ThreadedObject's directly, instead I pass them onto a queue (via std::function) to be executed within the correct thread (parentThread).
I ran into an issue with the initialize method. The intent of this method is to act as a thread-conscious "constructor." What I mean is, since a ThreadedObject can be created in ANY thread, that means its constructor will run in the thread is was created in. However, I want the initialization (that would normally be in the constructor) to occur within the parent thread of the ThreadedObject instance.
The simplest solution to this problem would be:
Thread myThread();
MyThreadedObject myObject(&myThread);
invoke(&myObject, &MyThreadedObject::initialize);
Assuming the invoke method looks at what thread is assigned to myObject and queues a call to initialize within that thread.
However, I am wondering if there is any way to have this happen automatically AFTER the object has been constructed. My naive solution was to do the following:
ThreadedObject::ThreadedObject(Thread* parentThread) {
//...
invoke(this, &ThreadedObject::initialize);
}
However, I learned quickly that you can't call a virtual method like this from within the constructor of a base class.
It looks to me as if I need some way to call initialize AFTER all the layers of constructors (base -> child 1 -> child 2 -> ...) have completed.
Is something like this possible?
Thanks!
EDIT
I found an article about the same problem here: Is there any automated way to implement post-constructor and pre-destructor virtual method calls?
I am wondering if my real question then becomes, is there a way to wrap the construction of ThreadedObjects and their child classes in some sort of critical section so that construction completes before any other threads can take over?

Related

Is there a safe way to have a std::thread as a member of a class?

I would like to use a class that manages a thread (or several threads). Using composition, this would look like:
class MyClass{
private:
std::thread mythread;
void _ThreadMain();
public:
MyClass();
// other fields
}
Because the default constructor for an std::thread is pointless, I would need to call it explicitly in MyClass constructor:
MyClass::MyClass() : mythread(&MyClass::_ThreadMain,this) {}
However, in this case the _ThreadMain method will be likely executed before MyClass is constructed, leading to any kind of weird behaviour. This is clearly unsafe. How can I fix this?
An obvious solution would be to use a pointer to std::thread instead, and add another member function:
void MyClass::Start(){
// This time mythread is of type std::thread*
mythread = new std::thread(&MyClass::_ThreadMain,this); // One could use std::unique_pointer instead.
}
which would fire up that thread. In this case it would be called after the class is constructed, which will be indeed safe.
However, I am wondering if there is any reasonable solution that would allow me not to use pointers for this. It feels like it should be possible somehow (hey, there must be a way to launch a thread when a class is constructed!), but I cannot come up with anything that would not cause troubles.
I have considered using a conditional variable so that the _ThreadMain waits till the constructor has done its work, but I cannot use one before the class is constructed, right? (This would also be unhelpful if MyClass was a derived class)
You can use a thread in combination with move semantics:
class MyClass final
{
private:
std::thread mythread;
void _ThreadMain();
public:
MyClass()
: mythread{} // default constructor
{
// move assignment
mythread = std::thread{&MyClass::_ThreadMain, this};
}
};
The move assignment operator is documented on the following page. In particular, it is noexcept and no new thread is created.
http://en.cppreference.com/w/cpp/thread/thread/operator%3D
There is no better way, in general, than having a separate Start function.
Suppose MyClass is a base class for some future (unknown) class Derived. If the thread is started while (or before) the MyClass constructor runs, it always risks calling the "wrong" implementation of some virtual function overridden by Derived.
The only way to avoid this is to have the thread wait until after Derived is fully constructed, and the only way to do that is to call some other function after the Derived constructor completes to tell the thread to "go"... Which means you must have some kind of separately-invoked Go function.
You might as well just have a separately-invoked Start function instead and forego the complexity of waiting.
[Update]
Note that, for complex classes, "Two-Phase Construction" is an idiom recommended by some. Starting the thread would fit seamlessly into the "initialization" phase.
Consider separating the task from the thread management and launching.
One class creates a runner and any synchronization primitives snd the like, The other handles launching it. This allows construction of the runnable to fail before threading starts.
It also means the runnable is fully constructed prior to it being run.
Now a first pass would have the runner be a std::thread, but some stuff helping with abort and cleanup and continuations can be useful.
The run object could be a simple callable, or could add extra supportmfor the runnable to interact with it.

Writing a simple event dispatcher in c++ -- how do I avoid self-referencing and recursion problems?

I am attempting to write a simple event dispatcher in C++. I am very new to this particular arena so please forgive my ignorance.
For the dispatch process, I have the following interface:
class listener
{
public:
virtual void triggerEvent(int id)=0;
};
Then to incorporate it, I simply implement it:
class A : public listener
{
public:
A();
void triggerEvent(int event);
.
.
.
B* b;
};
In a class which has a listener pointer called listener_ that points to an A object, an event in A can be triggered as shown,
void B::method()
{
.
.
.
listener_->triggerEvent(DO_SOMETHING); // calling point
}
But now the problem is, is that A also has a pointer to a B object such that when A's triggerEvent implementation is called, B::method() is called right back again, i.e.:
void A::triggerEvent(int id)
{
if(id==DO_SOMETHING)b->method();
}
This then causes problems of recursion.
Ideally, I want the 'calling point' in B::method() to be immediately freed from the stack. How do I do this so that the above recursion problems are prevented? What is incorrect about my event dispatcher design? How do I fix it?
EDIT: Shown above is a very extreme example. In a real situation, A might actually be some `control thread'. B might then be a separate algorithm that needs to indicate to the control thread when its finished so that A can proceed with further operations. B::method might also be a thread.
Thanks and best wishes,
Ben.
You're implementing the observer pattern.
What is incorrect about my event dispatcher design?
The fact that you call the method that triggers the events inside an event handler. You fix it by not calling the method.

Why overloaded member not being called from thread?

I have a slightly modified version of the thread class copied off the Linux Self Help site that I have used to create a threading base class:
class Thread
{
public:
static void *entry (void *pvArg) { Thread *pobjThread = static_cast<Thread *> (pvArg); pobjThread->run (); }
virtual void run (void) = 0;
};
I have 2 thread classes:
class Item : public Thread
and
class Product : public Thread
class Item starts the thread from the constructor of the function, which class into pthread library to create the thread calling entry with this as the pvArg while class Product creates it's thread later during programme execution.
Now the thing is, class Item works fine. The runfunction is called and processes correctly. However, when class Product calls the same function later, I get:
pure virtual method called
Both class have the same implementation with overloading the run method, but one is called and the other is not.
Why would I suddenly get a pure virtual method called exception?
Thanks.
Update:
class Item is different the class Product because Item is declared as a static Item item; in the cpp file and there is only one. class Product is used like a normal object. If I do the same thing to class Product it works fine.
Do not call virtual functions from a constructor or a destructor - the inheritance chain is incomplete when code is running in either, and as such, there's no meaningful way to call virtual functions. See Pure virtual invocation from constructor and destructor for another answer.
Item and Product are : public Thread means you would call a virtual function (of itself) inside the constructor. Inside the constructor the vtable is not set up fully yet (since it depends on each of base classes being initialized), so you will get undefined behavior.
best practice: dont call virtual functions from inside a constructor/destructor. Keep constructors/destructors very simple, do the rest of the work inside an init() function or such.
Thanks to what modelnine pointed out, we found the offending code was creating an object, starting the thread and then destroying the object, before the thread got a chance to run. This, as modelnine indicated, delete's the vtable, and this caused the problem.
Thanks to modelnine in the comments of the question.

Why can't I call a class's start function from within itself?

I'm totally new to programming with threads, and since the class is using QThreads, I'm wondering why I cannot call a QThread's start function from within itself and have its run function start executing independently of another thread (the program seems to crash when I do this). Instead, I have to call the start function from wherever the object was declared. Why is this?
Some code:
class ClassWithThread : public QThread
{
public:
ClassWithThread() {}
someFunction() {start();}
run()
{
//do some stuff here
}
}
That is basically what my class does. When I call someFunction the program crashes. If I remove the start statement from someFunction though, and call start from outside the program, then it works fine.
QThread should be derived only if you want to extend thread capability, not to specialize it for your job like this. This article would help you to understand the use of QThread.
So you must create a QThread and start it from outside and then move an object to it that will do the job. Read this example: http://labs.qt.nokia.com/2006/12/04/threading-without-the-headache/
Hope that helps to avoid this kind of problem

C++ using this pointer in constructors

In C++, during a class constructor, I started a new thread with this pointer as a parameter which will be used in the thread extensively (say, calling member functions). Is that a bad thing to do? Why and what are the consequences?
My thread start process is at the end of the constructor.
The consequence is that the thread can start and code will start executing a not yet fully initialized object. Which is bad enough in itself.
If you are considering that 'well, it will be the last sentence in the constructor, it will be just about as constructed as it gets...' think again: you might derive from that class, and the derived object will not be constructed.
The compiler may want to play with your code around and decide that it will reorder instructions and it might actually pass the this pointer before executing any other part of the code... multithreading is tricky
Main consequence is that the thread might start running (and using your pointer) before the constructor has completed, so the object may not be in a defined/usable state. Likewise, depending how the thread is stopped it might continue running after the destructor has started and so the object again may not be in a usable state.
This is especially problematic if your class is a base class, since the derived class constructor won't even start running until after your constructor exits, and the derived class destructor will have completed before yours starts. Also, virtual function calls don't do what you might think before derived classes are constructed and after they're destructed: virtual calls "ignore" classes whose part of the object doesn't exist.
Example:
struct BaseThread {
MyThread() {
pthread_create(thread, attr, pthread_fn, static_cast<void*>(this));
}
virtual ~MyThread() {
maybe stop thread somehow, reap it;
}
virtual void id() { std::cout << "base\n"; }
};
struct DerivedThread : BaseThread {
virtual void id() { std::cout << "derived\n"; }
};
void* thread_fn(void* input) {
(static_cast<BaseThread*>(input))->id();
return 0;
}
Now if you create a DerivedThread, it's a best a race between the thread that constructs it and the new thread, to determine which version of id() gets called. It could be that something worse can happen, you'd need to look quite closely at your threading API and compiler.
The usual way to not have to worry about this is just to give your thread class a start() function, which the user calls after constructing it.
Depends on what you do after starting the thread. If you perform initialization work after the thread has started, then it could use data that is not properly initialized.
You can reduce the risks by using a factory method that first creates an object, then starts the thread.
But I think the greatest flaw in the design is that, for me at least, a constructor that does more than "construction" seems quite confusing.
It can be potentially dangerous.
During construction of a base class any calls to virtual functions will not despatch to overrides in more derived classes that haven't yet been completely constructed; once the construction of the more derived classes change this changes.
If the thread that you kick-off calls a virtual function and it is indeterminate where this happens in relation to the completion of the construction of the class then you are likely to get unpredictable behaviour; perhaps a crash.
Without virtual functions, if the thread only uses methods and data of the parts of the class that have been constructed completely the behaviour is likely to be predictable.
I'd say that, as a general rule, you should avoid doing this. But you can certainly get away with it in many circumstances. I think there are basically two things that can go wrong:
The new thread might try to access the object before the constructor finishes initializing it. You can work around this by making sure all initialization is complete before you start the thread. But what if someone inherits from your class? You have no control over what their constructor will do.
What happens if your thread fails to start? There isn't really a clean way to handle errors in a constructor. You can throw an exception, but this is perilous since it means that your object's destructor will not get called. If you elect not to throw an exception, then you're stuck writing code in your various methods to check if things were initialized properly.
Generally speaking, if you have complex, error-prone initialization to perform, then it's best to do it in a method rather than the constructor.
Basically, what you need is two-phase construction: You want to start your thread only after the object is fully constructed. John Dibling answered a similar (not a duplicate) question yesterday exhaustively discussing two-phase construction. You might want to have a look at it.
Note, however, that this still leaves the problem that the thread might be started before a derived class' constructor is done. (Derived classes' constructors are called after those of their base classes.)
So in the end the safest thing is probably to manually start the thread:
class Thread {
public:
Thread();
virtual ~Thread();
void start();
// ...
};
class MyThread : public Thread {
public:
MyThread() : Thread() {}
// ...
};
void f()
{
MyThread thrd;
thrd.start();
// ...
}
It's fine, as long as you can start using that pointer right away. If you require the rest of the constructor to complete initialization before the new thread can use the pointer, then you need to do some synchronization.