Alex Rivera | Logout

Using boost thread and a non-static class function

Asked 2011-01-03T01:17:10.073
46

So I have done some research, and have found you can create a boost::thread object and have it start with a non-static class function by using "this" and boost::bind etc. It really doesn't make much sense to me and all the examples I could find had the boost::thread object launched within the same class as the function it was starting with so this could be used. I however, am launching the thread in a different class so I'm afraid by using "this", I will be saying the "this" is from the class I am creating the thread from, rather than the one the function is in (I'm probably wrong, I need to learn more about this "this" guy). Here is an example of my source I am having the problem with.

ANNGUI.h

class ANNGUI
{
private:
    boost::thread *GUIThread;
    Main *GUIMain;
public:
    // Creates the entire GUI and all sub-parts.
    int CreateGUI();
}

ANNGUI.cpp

int ANNGUI::CreateGUI()
{
        GUIMain = new Main();
    GUIThread = new boost::thread(GUIMain->MainThreadFunc);
};

This isn't all the source, but I think my problem is in here somewhere, I know I have to deal with the "this" somehow, but I'm unsure how. I Could use a static function, but I didn't really want to make my variables static either. Thanks.

Also, Is there any very good resource for using any boost libraries? Their web site documentation seems good, but over my head.

Edit
Report

1 Answer

3

In cases like this it is useful to think of non-static member functions as free functions that take the this as first parameter, for example in your case void MainThreadFunc(Main* this).

boost::thread accepts a nullary functor, so you have to pass it a nullary functor which contains a reference to the instance GUIMain and calls GUIMain->MainThreadFunc which, seen as I explained above, would be something like MainThreadFunc(GUIMain).

Boost (and now also C++ with TR1) provides helpers to create such functors, namely boost::bind (or alternatively boost::lambda::bind). The expression boost::bind(f, arg1, arg2, ...) means "return a nullary functor which calls f(arg1, arg2, ...)".

That said, you can use the following expression to create the thread:

GUIThread = new boost::thread(boost::bind(&Main::MainThreadFunc, GUIMain))
answered 2011-01-03T01:30:05.357

Your Answer