how to call a thread member function from main ( ) - c++

I'm getting errors while compiling a program that uses threads. Here is the part that is causing problems.It would be nice if anybody told me if I'm calling the thread function in the right way .
In main.cpp:
int main()
{
WishList w;
boost::thread thrd(&w.show_list);
thrd.join();
}
In another_file.cpp:
class WishList{
public:
void show_list();
}
void WishList::show_list(){
.
.
.
.
}
I'm getting the following error
error: ISO C++ forbids taking the address of a bound member function to form a pointer to member function. Say ‘&WishList::show_list’
/home/sharatds/Downloads/boost_1_46_1/boost/thread/detail/thread.hpp: In member function ‘void boost::detail::thread_data<F>::run() [with F = void (WishList::*)()]’:
/home/sharatds/Downloads/boost_1_46_1/boost/thread/detail/thread.hpp:61:17: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘((boost::detail::thread_data<void (WishList::*)()>*)this)->boost::detail::thread_data<void (WishList::*)()>::f (...)’, e.g. ‘(... ->* ((boost::detail::thread_data<void (WishList::*)()>*)this)->boost::detail::thread_data<void (WishList::*)()>::f) (...)’
EDIT : Having problems installing Boost library for threads. Shall try this as soon as it works

The syntax to take the address of a member function is &ClassName::FunctionName, so it should be &WishList::show_list, but now you need an object to call the function pointer on. Best (and easiest) is to use boost::bind:
#include <boost/bind.hpp>
WishList w;
boost::thread t(boost::bind(&WishList::show_list, &w));

Nothing to do with threads, this is just "how do I obtain a pointer to a member function". Do what the compiler says, say &WishList::show_list. But you may also need to pass the instance pointer along.
Update: Yes, use bind like Xeo says.
Regarding your title: Note that the function does not "belong to the thread". Classes are not part of threads. All threads access the same memory -- each thread has its own space for automatic storage, but there's nothing in a class definition that says "this goes in a separate thread".

Related

Qt Concurrent: call member function from another class

In Qt Creator, using C++ I have to call the same function from another class for many times. However this slows down the overall performance speed. So in order to do real-time operation, I thought of using multithreading. After some search I found Qt Concurrent might help so tried the following steps.
My target function is in this class:
Class myClass
{
public foo(std::vector<float> inputVec, std::string inputStr);
}
And in my main class, I do this:
std::vector<float> mvec;
// here put some values into mvec;
std::string mstring = "test";
myClass mcl;
QFuture<float> f1 = QtConcurrent::run(mcl.foo(mvec, mstring));
f1.waitForFinished();
However, this gives out error saying:
no matching function for call to 'run(float)'
'functor' cannot be used as a function
'float' is not a class, struct, or union type
...
I also tried to use std::thread like this:
std::thread t1 = std::thread(mcl.foo, mvec, mstring);
if(t1.joinable()) t1.join();
But this throws the following error:
invalid use of non-static member function
I've tried many example codes online but still confused. How can I make this code to run smoothly and thread safe? Thank you.
The following statement, executes the foo method and passes the result of it to the run function.
QtConcurrent::run(mcl.foo(mvec, mstring));
The correct form is:
QtConcurrent::run(&mcl, &myClass::foo, mvec, mstring);
Also note that calling f1.waitForFinished(); after that, actually blocks your thread until the foo method completes. So you won't gain any advantage of multithreading.
You have to pass the (member-)function itself (plus the object the member shall relate to), not the result of just calling it. Have a look at the documentation:
QtConcurrent::run() also accepts pointers to member functions. The
first argument must be either a const reference or a pointer to an
instance of the class. Passing by const reference is useful when
calling const member functions; passing by pointer is useful for
calling non-const member functions that modify the instance.
For example, calling QByteArray::split() (a const member function) in
a separate thread is done like this:
// call 'QList<QByteArray> QByteArray::split(char sep) const' in a
separate thread QByteArray bytearray = "hello world";
QFuture<QList<QByteArray> > future = QtConcurrent::run(bytearray, &QByteArray::split, ',');
...
QList<QByteArray> result = future.result();
Thus, your code should rather look like
myClass mcl;
QFuture<float> f1 = QtConcurrent::run(&mcl, &myClass::foo, mvec, mstring);
f1.waitForFinished();

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.

Creating a boost::thread with boost::bind() or without

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.

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.