I have code where objects that are designed to be executed in a separate thread are retrieved from a base class with a pure virtual Run function. I cannot get the following (simplified test code) to start a 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 (that's half the battle), but "Hello" never gets printed. If I were doing something wrong, I would have guessed a runtime error at some point. I am using gcc.
Edit: the above code will not compile on VS2012, with: error C2064: term does not evaluate to a function taking 0 arguments
You need to use lambda instead of std::ref , i.e.
void ThreadTest(Base& aBase) { std::thread t([&] () { aBase.Run(); }); t.join(); }
c ++ multithreading c ++ 11 visual-studio-2012
James
source share