tzippy
tzippy

Reputation: 6638

C++ Calling member function in boost thread

So I want to start member function Open() in a boost thread:

.hpp

Class MyClass{
  public:
    int Open();
  private:
    void handle_thread();
};

.cpp

int MyClass::Open(){
    boost::thread t(handle_thread);
    t.join();
    return 0;
}

void MyClass::handle_thread(){
  //do stuff
}

test.cpp
int main(){
     MyClass* testObject = new MyClass()
     testObject.Open();
}

This results in a compiler error.

error: no matching function for call to 'boost::thread::thread(<unresolved overloaded function type>)'

I see that Open() doesn't know on which object to call handle_thread. But I cannot figure out what the correct syntax is.

Upvotes: 2

Views: 4196

Answers (1)

ComicSansMS
ComicSansMS

Reputation: 54589

handle_thread is a member function and must be called as such:

int MyClass::Open(){
    boost::thread t(&MyClass::handle_thread, this);
    ...
}

Note that if you jointhe thread immediately afterwards, you function will be blocking. The behavior will be identical to that of a single-threaded application, besides the fact that handle_thread actually runs on a different thread. There will be no interleaving of threads (i.e. no parallelism) though.

Upvotes: 1

Related Questions