0

I'm trying to make a thread to callback a function of the object that created the thread. But it seems it is not posible to pass "this" as a parameter. Is there a way to implement this? Thanks in advance.

Helper.cpp

void Helper::ProcessSomething(void (*callback)(void))
{
    boost::this_thread::sleep(boost::posix_time::seconds(1));
    callback();
}

SomeClass.cpp

void SomeClass::Start(void)
{
    Helper *helper = Helper();
    boost::thread t(&Helper::ProcessSomething, helper, &this->SomeCallback);
    t.join();
}

void SomeClass::SomeCallback(void)
{
    std::cout << "Callback called" << std::endl;
}

1 Answers1

2

The problem is that SomeCallback is not static (at least not that I can see), so there is another this unaccounted for in thread's constructor. Further, because it's not static, you can't convert SomeCallback to the void(*)(void) that ProcessSomething requires.

The simplest fix would just be to make SomeCallback static (and change &this->SomeCallback to &SomeClass::SomeCallback). But if you can't, this is a possible workaround (I'm assuming you don't have C++11):

void Helper::ProcessSomething(boost::function<void()> callback)
{
    boost::this_thread::sleep(boost::posix_time::seconds(1));
    callback();
}

// ...

void SomeClass::Start(void)
{
    Helper *helper = Helper();
    boost::function<void()> callback = boost::bind(&SomeClass::SomeCallback, this);
    boost::thread t(&Helper::ProcessSomething, helper, callback);
    t.join();
}

If you do have C++11 (but want to use boost::thread anyway), you could use a lambda instead of a binding:

void SomeClass::Start(void)
{
    Helper *helper = Helper();
    boost::thread t(&Helper::ProcessSomething, helper, [this]() { SomeCallback(); });
    t.join();
}
dlf
  • 9,045
  • 4
  • 32
  • 58