Using boost thread and a non-static class function

后端 未结 5 1103
清酒与你
清酒与你 2020-11-30 19:57

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.

5条回答
  •  猫巷女王i
    2020-11-30 20:27

    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))
    

提交回复
热议问题