Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass an instance member function as callback to std::thread [duplicate]

Possible Duplicate:
Start thread with member function

I'm VERY new to C++. My experience has mostly been with javascript and java.

I'm using Xcode on Lion. The following code gives me a compilation error "Reference to non-static member function must be called; did you mean to call it with no arguments?"

class MyClass {
private:
    void handler() {
    }

public:
    void handleThings() {
        std::thread myThread(handler);
    }
};

I also tried this->handler, &handler, and other variations, but none of them worked. This code compiles though and accomplishes what I want it to:

class MyClass {
private:
    void handler() {
    }

public:
    void handleThings() {
        std::thread myThread([this]() {
            handler();
        });
    }
};

Why can't I pass a reference to a member function? Is my work-around the best solution?

like image 433
Trevor Dixon Avatar asked Jan 22 '13 07:01

Trevor Dixon


1 Answers

std::thread myThread(&MyClass::handler, this);
myThread.join();
like image 176
Pete Becker Avatar answered Nov 15 '22 05:11

Pete Becker