Why overloaded member not being called from thread? - c++

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.

Related

Automatically Call Method After Final Constructor

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?

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.

Issues while making a java like runnable class in C++

I've been trying to create a runnable class in order to interface multi-threaded classes just like java-folks do. But I can't seem to use _beginthread with the virtual function run.
I'm getting the following error:
'beginthread' : cannot convert parameter 1
from 'void (_cdecl Runnable::* )(void *)' to 'void (__cdecl *)(void *)'
#include "CriticalSection.h"
#include <stdio.h>
#include <conio.h>
#include <process.h>
class Runnable{
private:
Runnable() { _beginthread(&Runnable::Run,0,(void*)0); }
~Runnable();
virtual void __cdecl Run ( void* ) = 0;
};
int main(){
//CriticalSection crt;
//ErrorHandler err;
//LockSection lc(&crt,&err);
while(!kbhit());
return 0;
}
There are two approaches to implementing multithreading libraries, both of them used in Java, with slightly different variants for C++. Since you seem to know Java, I will discuss the approaches there:
Deriving from Thread
In this approach, there is a base class that represents a thread, from which you inherit and implement a method that will be called when the thread starts. The base thread class offers control over the thread, and derived classes implement a run (or equivalent) method. The base thread class must not start the actual thread, but let user code start it through a member method start. The reason for this is that if the base thread class started the thread, the newly spawned thread might try to call the overridden method before the full object is created. This has the nasty side effect of calling the overrider in the base thread class in C++, or calling the final overrider of the run method on a yet uninitialized object in Java. --Unsafe in both cases.
Runnable interface
To reduce the possibility of causing undefined behavior, and to separate responsibilities, the second approach distinguishes thread control from the implementation of the code that is to be run in the newly spawned thread. A thread class is created, but not meant to be used as a base class. Rather an interface is offered for Runnable objects. User code will derive from that interface and pass an object to the thread class. The design ensures that the previous error cannot be done, as the Runnable must be fully created before passing it to the thread.
Modern C++ approach to the Runnable interface
The new standard threading libraries (and boost thread) offer an approach similar to the Runnable interface, with a couple of differences. The first is that user code does not need to fullfill a concrete interface but can actually tell the threading library what method of the class is to be run and with what arguments. This is implemented by applying type erasure in the constructor of the thread class, where the exact type of the user arguments are erased for later use inside the thread. This has the same advantages as the Runnable version --ensures that the object is fully created before the thread is spawned. At the same time, it removes the requirement of having to implement an exact interface, which means that you will be able to use a free function, or a member function of a class together with the instance on which that member function is to be called, or a functor that implements operator()...
If you are going to be coding in C++ I recommend that you use the last approach, as that is the most flexible for user code, and at the same time it is safer than what you are trying to do. That is, do not reinvent the wheel, there are good well thought C++ threading libraries (C++11 if you have it, boost if you don't --or Poco, or ACE...) that will avoid many of the pitfalls.
One really important bit to remember is that, whatever the approach you follow, you must ensure that the new thread does not try to call a virtual function in an object that is not fully created, as that will cause Undefined Behavior.
Even if what you wrote compiled as you expected, it wouldn't behave correctly. You are starting a thread in your constructor that will call a pure virtual function on this. But virtual dispatch while constructors are running does not dispatch to classes more derived that the one that is running the constructor.
If that code compiled, you would have a race condition: the virtual call could occur before the constructor of Runnable ended, or while a subclass constructor was running, or after they all ran. Each of these would have a different outcome, and the first one would probably crash.
You need the function to be passed to _beginthread to be static.
I suggest you read this article by Herb Sutter and try to implement the Active Object Pattern.
Use Boost.Thread or C++11 std::thread. Pointers to members are different than ordinary pointers to functions, so you cannot pass them to a C library (they require this pointer to be present, and library cannot handle it, because there is no such thing in C).

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.