I have code where objects that are intended to execute in separate thread derive from a base class with a pure virtual Run
function. I cannot get the following (simplified test code) to run the new thread.
#include <iostream>
#include <thread>
#include <functional>
class Base {
public:
virtual void Run() = 0;
void operator()() { Run(); }
};
class Derived : public Base {
public:
void Run() { std::cout << "Hello" << std::endl; }
};
void ThreadTest(Base& aBase) {
std::thread t(std::ref(aBase));
t.join();
}
int main(/*blah*/) {
Base* b = new Derived();
ThreadTest(*b);
}
The code compiles fine (which is half the battle) but "Hello" never gets printed. If I was doing something wrong I'd expect a runtime error at some point. I'm using gcc.
Edit: The code above fails to compile on VS2012, with:
error C2064: term does not evaluate to a function taking 0 arguments
You need to use a lambda instead of std::ref
, i.e.
void ThreadTest(Base& aBase)
{
std::thread t([&] ()
{
aBase.Run();
});
t.join();
}
You need to add -pthread to g++ command line, as explained in this answer to a similar question: https://stackoverflow.com/a/6485728/39622.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With