Creating a boost::thread with boost::bind() or without - c++

Some people seem to launch boost::threads using the boost::bind() function, like in the accepted answer of the following question:
Using boost thread and a non-static class function
Whereas other people don't use it at all, like in the answer with the most upvotes of this question:
Best way to start a thread as a member of a C++ class?
So, what's the difference, if it exists?

As you can see by the code below that compile and gives the expected output, boost::bind is completely unnecessary for using boost::thread with free functions, member functions and static member functions:
#include <boost/thread/thread.hpp>
#include <iostream>
void FreeFunction()
{
std::cout << "hello from free function" << std::endl;
}
struct SomeClass
{
void MemberFunction()
{
std::cout << "hello from member function" << std::endl;
}
static void StaticFunction()
{
std::cout << "hello from static member function" << std::endl;
}
};
int main()
{
SomeClass someClass;
// this free function will be used internally as is
boost::thread t1(&FreeFunction);
t1.join();
// this static member function will be used internally as is
boost::thread t2(&SomeClass::StaticFunction);
t2.join();
// boost::bind will be called on this member function internally
boost::thread t3(&SomeClass::MemberFunction, someClass);
t3.join();
}
Output:
hello from free function
hello from static member function
hello from member function
The internal bind in the constructor does all the work for you.
Just added a few extra comments on what happens with each function type. (Hopefully I've read the source correctly!) As far as I can see, using boost::bind externally will not cause it to also double up and be called internally as it will pass through as is.

There is no difference - thread contructor uses bind internally.
People use bind explicitly for historical reasons, because Boost.Thread didn't have a "binding" constructor before 1.36.

The boost::bind is used to bind a member function to a thread, whereas without boost::bind normally you're using a static function or a free function with the thread.

So, what's the difference, if it exists?
The main difference is what do you need to access within the thread function.
If your design requires that you access a class instance's data, then launch your thread as part of a class instance (use boost::bind with this and a member function, or a static member function with a void* mapped to this - that's a matter of style mostly).
If your design requires that the thread function is not dependent on a particular object's data, then use a free function.

The primary difference is whether you want to interface static or non-static member functions. If you want to use non-static member functions as the function launched by the thread, you must use something like bind.
The proposed alternative (the second question you linked) is to use a static method that takes a pointer to the class object and can then call any of it's members. This clears up the syntax slightly but the biggest advantage (to me) is that you don't need to include something like Boost to get bind. But if you are using boost::threads you might as well take boost::bind also. Note, C++ 11 has std::bind so you could use bind with pthreads as well and not introduce any extra dependency such as Boost, but that's if you want to use C++ 11.
I don't see a compelling syntax reason to avoid using bind over having a static method that calls member functions. But that is more a matter of personal preference.

Related

passing an argument to a boost::thread constructer [duplicate]

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.
The this keyword is used with boost::bind when the function object you're creating is bound to a object member function. Member functions can't exist apart from instances, so when creating a functor object out of a member function with boost::bind, you need a pointer to an instance. That's exactly what the this keyword actually is. If you use the this keyword within a member function of a class, what you get is a pointer to the current instance of that class.
If you were to call bind from outside a class member function, you might say something like:
int main()
{
Foo f;
boost::thread* thr = new boost::thread(boost::bind(&Foo::some_function, &f));
}
Here, we're using Foo::some_function as our thread function. But we can't use this because we're calling bind from main. But the same thing could be achieved using this if we called bind from within a member function of Foo, like so:
void Foo::func1()
{
boost::thread* thr = new boost::thread(boost::bind(&Foo::some_function, this));
}
If a member function is static, or is simply a regular (non-member) function, then you don't need an instance pointer at all. You would just do:
boost::thread* thr = new boost::thread(some_regular_function);
As others mentioned, when you want to call an object method in a new thread, you have to supply the address of that object. But you don't need to call boost::bind, you can use the overloaded boost::thread constructor like this:
GUIThread = new boost::thread(&Main::MainThreadFunc, GUIMain);
If the method is in the same class you use this to get the address of the current instance, e.g.:
t = new boost::thread(&myclass::compute, this);
If the method has parameters, you can specify them after the second argument, e.g.:
t = new boost::thread(&myclass::compute, this, p1, p2);
boost::bind is your friend (it can sometimes have a rough way of showing it though)!
use GUIThread = new boost::thread(boost::bind(&Main::MainThreadFunc, GUIMain));
and then make your MainThreadFunc a regular member. That means that you can use the instance variables directly like you would normally do.
Something like this:
class GUIMain {
public:
GUIMain() : m_Member(42) {}
void MainThreadFunc() {
// use all members as you would normally do
std::cout << m_Member << std::endl;
}
private:
int m_Member;
};
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))
If your object is a functor, i.e. has an operator(), you can pass an instance of it to boost::thread. The operator() does not need to be static. For example:
#include <boost/thread.hpp>
struct th {
void operator()();
};
void th::operator()()
{
for (;;) {
// stuff
}
}
int main()
{
th t;
boost::thread my_thread( t ); // takes a copy of t !
my_thread.join(); // blocks
return 0;
}

c++11 thread, static or non-static class member function, meaning of arguments

I have been playing with the c++11 thread for a while, and have some questions. People say that when you call a class member function in thread, this function has to be static. But it seems that this is not true. For example, I found this:
class bar
{ public:
void foo() {std::out << "Hello" << std::endl};
}
int main()
{
std::thread t0(&bar::foo, bar());
t0.join();
}
The above code works fine. It seems that the member function do not have to be static in c++11 standard. I want to know if my understanding is true. Another question is that, if I simply modify "void foo()" with "static void foo()", I get an error:
error: no type named 'type' in 'class std::result_of<void (*(bar))()>'
I do not understand this, but it seems that this is because the way I call the thread is not correct. I am very confuse in calling a function in a thread. For example, I found another way to call the same member function in the above example as
int main()
{ bar A;
std::thread t0(&bar::foo, &A);
}
It works also! I don't know the difference between these two ways. It seems that in the first way the constructor of the class will be performed each time I call foo(), while the in the second one it will not. Is that true? Besides, when calling member function in another class member function, the 'this' has to be passed.
I search the internet, all I can find is examples, without explaining the meaning of the arguments. Can anyone tell me how should I set the arguments (especially the first three) in a std::thread?
std::thread t0(&bar::foo) works pretty fine with static foo method.
Also, when asking a question consider to provide working code but not your text what you actually wrote just now right in the text field of this site.
Short answer to your question: provide this parameter to non-static class methods or don't provide it if it is static class method.
But, if you don't understand even that you must know one thing:
each class method works with this object which means a constant pointer to current object. While binding your function (I guess exactly binding works inside std::thread) the first parameter must be the object which method you want to call. Otherwise it is meaningless: you are trying to do something with what object then? The this exists in each non-static method of the class, implicitly, by first parameter of the method.
I recommend you to read the definitive c++ stackoverflow book guide and list

Using c++ 11 multithreading on non-static member function

So, my problem is this:
I have a class called NetworkInterface that is built using the RakNet networking library.
It holds a method that uses the while loop that RakNet uses to send and receive data.
Now, I made the NetworkInterface class a singleton because I want it to only exist once throughout my game I'm writing.
But, if I'd just call the method with the while loop it would stop my whole gqme so thqt's why I wanted it to run on a different thread so it doesn't interfere with the game mechanics.
Now, I used the std::thread object to start the method in NetworkInterface on a different thread but it throws the C3867 error which states that the method needs to be static or some sort (I found this on Google already) but I don't know how to fix this because I have variables that are used in that method that can't be static as well.
I hope this is clear. In short, how would I implement a non-static method from a class in a seperate thread of my program. Or is there a better way? (I don't want to use the Boost library if that pops up)
You need to provide an object for you to call a non-static member function, just as you can't call method() on its own. To provide that object, pass it to std::thread's constructor after the argument where you put the function.
struct Test {
void func(int x) {}
};
int main() {
Test x;
std::thread t(&Test::func, &x, 42);
t.join();
}
LIVE EXAMPLE
Notice that I've passed &x. This is because non-static class functions accepts a pointer to the object where it is being called from, and this pointer is the this pointer. The rest, which is 42, is the arguments that corresponds to the method's parameter declaration with 42 coinciding with int x in the example.

Using boost thread and a non-static class function

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.
The this keyword is used with boost::bind when the function object you're creating is bound to a object member function. Member functions can't exist apart from instances, so when creating a functor object out of a member function with boost::bind, you need a pointer to an instance. That's exactly what the this keyword actually is. If you use the this keyword within a member function of a class, what you get is a pointer to the current instance of that class.
If you were to call bind from outside a class member function, you might say something like:
int main()
{
Foo f;
boost::thread* thr = new boost::thread(boost::bind(&Foo::some_function, &f));
}
Here, we're using Foo::some_function as our thread function. But we can't use this because we're calling bind from main. But the same thing could be achieved using this if we called bind from within a member function of Foo, like so:
void Foo::func1()
{
boost::thread* thr = new boost::thread(boost::bind(&Foo::some_function, this));
}
If a member function is static, or is simply a regular (non-member) function, then you don't need an instance pointer at all. You would just do:
boost::thread* thr = new boost::thread(some_regular_function);
As others mentioned, when you want to call an object method in a new thread, you have to supply the address of that object. But you don't need to call boost::bind, you can use the overloaded boost::thread constructor like this:
GUIThread = new boost::thread(&Main::MainThreadFunc, GUIMain);
If the method is in the same class you use this to get the address of the current instance, e.g.:
t = new boost::thread(&myclass::compute, this);
If the method has parameters, you can specify them after the second argument, e.g.:
t = new boost::thread(&myclass::compute, this, p1, p2);
boost::bind is your friend (it can sometimes have a rough way of showing it though)!
use GUIThread = new boost::thread(boost::bind(&Main::MainThreadFunc, GUIMain));
and then make your MainThreadFunc a regular member. That means that you can use the instance variables directly like you would normally do.
Something like this:
class GUIMain {
public:
GUIMain() : m_Member(42) {}
void MainThreadFunc() {
// use all members as you would normally do
std::cout << m_Member << std::endl;
}
private:
int m_Member;
};
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))
If your object is a functor, i.e. has an operator(), you can pass an instance of it to boost::thread. The operator() does not need to be static. For example:
#include <boost/thread.hpp>
struct th {
void operator()();
};
void th::operator()()
{
for (;;) {
// stuff
}
}
int main()
{
th t;
boost::thread my_thread( t ); // takes a copy of t !
my_thread.join(); // blocks
return 0;
}

Why callback functions needs to be static when declared in class

I was trying to declare a callback function in class and then somewhere i read the function needs to be static but It didn't explain why?
#include <iostream>
using std::cout;
using std::endl;
class Test
{
public:
Test() {}
void my_func(void (*f)())
{
cout << "In My Function" << endl;
f(); //Invoke callback function
}
static void callback_func()
{cout << "In Callback function" << endl;}
};
int main()
{
Test Obj;
Obj.my_func(Obj.callback_func);
}
A member function is a function that need a class instance to be called on.
Members function cannot be called without providing the instance to call on to. That makes it harder to use sometimes.
A static function is almost like a global function : it don't need a class instance to be called on. So you only need to get the pointer to the function to be able to call it.
Take a look to std::function (or std::tr1::function or boost::function if your compiler doesn't provide it yet), it's useful in your case as it allow you to use anything that is callable (providing () syntax or operator ) as callback, including callable objects and member functions (see std::bind or boost::bind for this case).
Callbacks need to be static so that they don't have an implicit this parameter as the first argument in their function signature.
Non-static methods require a 'this' instance, and can only be called upon an object instance.
However, it is possible to use non-static callbacks, but they are syntactically much harder to write. See http://www.newty.de/fpt/callback.html#member for an explanation.
Marshal Cline gives you the complete answer here
. The whole section contains everything you need to know.
To summarize it can explain that you need a static member because the this pointer isn't needed (unlike normal member methods). But it also covers that using a static may not be enough for all compilers since C++ calling convention might be different between C and C++.
So the recommendation is to use an extern "C" non-member function.
It needs to be static so that the function signature matches. When a member function is called, a hidden parameter is included in the call (i.e. the "this" pointer). In static member functions the this pointer is not passed as a parameter.
If you use function pointers, the runtime environment can't pass a reference to an instance when calling the function. But you may use std::mem_fun<>, in to use functors and member methods.