Using C ++ 11 thread with pure virtual thread function

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(); } 
+8
c ++ multithreading c ++ 11 visual-studio-2012
source share
1 answer

You need to add the -pthread command line in g ++, as explained in this answer to a similar question: https://stackoverflow.com/a/464829/

+3
source share

All Articles