Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C++11 thread with pure virtual thread function

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();
}
like image 351
James Avatar asked Jan 30 '13 17:01

James


1 Answers

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

like image 126
Cyrille Ka Avatar answered Sep 20 '22 09:09

Cyrille Ka