Using threads with Classes in C++ - c++

Say I have an object called myObject of class myClass. It has a function
void myFunction()
What is the syntax to call this function with a thread?
I tried
std::thread myThread(myObject.myFunction)
but I'm given a syntax error and can't seems to find the correct syntax.
The error message is:
function "std::thread::thread(const std::thread &)" cannot be referenced -- it is a deleted function
Thanks for any help.

You can write:
std::thread myThread(std::bind(&myClass::myFunction, myObject));
Being, myClass the class name of myObject. This is the syntax for a pointer-to-member-function.
Also, you can add any other argument your myFunction requires just after myObject.

according to GCC , here is the error : http://coliru.stacked-crooked.com/a/4fcba365c9b25d1e
which makes sense, because member function is bound to this pointer , member variabes and many more. I'd go with lambda expression :
std::thread t ([&]{
myObject.myFunction();
})
working example : http://coliru.stacked-crooked.com/a/0be834a7249bfac9
btw, this practice of wrapping everything with anonymous function is very common in JavaScript, and should be used also here

Possible duplicate.
std::thread myThread(&myClass.myFunction, myObject)

Related

Starting a thread or future with an std::string () const function [duplicate]

This question already has answers here:
Start thread with member function
(5 answers)
Closed 4 years ago.
I would like to spawn a thread or a future calling this function:
std::string myClass::myFunction() const noexcept
I first tried spawning them both like this:
thread t0(myFunction); auto f1 = async(myFunction);
I would then get this error:
no instance of constructor "std::thread::thread" matches the argument list. argument types are: (std::string () const)
I then read online that since it is const I would need to call it by reference but all methods online have not worked, I am unsure if the problem is because the function is const or not.
What I have tried:
thread t0(&myClass::myFunction); auto f1 = async(&myClass::myFunction);
and
thread t0(&myFunction); auto f1 = async(&myFunction);
After this I would have two new errors that I cannot find a solution to:
std::invoke: no matching overloaded function found.
and
Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'
I think this is due to my lack of understand on how threads and futures work but I am struggling to find literature that gives me any relation to this.
Basically I don't really understand what rule I am breaking, if there is a fundamental flaw in my approach any direction or tips would be nice. Thank you for your time.
std::string myClass::myFunction() const noexcept
This is not a function. This is a class method. There is a fundamental different between the two.
You cannot simply write
myFunction();
Somewhere in your code, other than in another method of the same class, which uses this to invoke a different method for the same instance of the class. Anywhere outside a method of the same class, myFunction(); won't compile, and your compilation error is the same exact reason. The first parameter to std::thread's constructor is a function, not a class method. It can be a class method, which I'll get to shortly. But your first error is confusion between the concept of a function and a class method, that you need to understand.
You could make myFunction() a static class function, which then works just like any, ordinary, function, and then feed it to std::thread as usual. Another option is to construct std::thread using a wrapper function that passes whichever class whose method you wish to invoke to the wrapper function, and the wrapper function uses it. The "whichever class" could be this:
void invoke_func(const myClass *ptr)
{
ptr->myFunction();
}
// ...
std::thread new_thread{ this };
Another, a more modern approach that can be used to invoke a class method is to pass an additional parameter, a pointer to an instance of the class whose method you wish to invoke:
std::thread new_thread{ &myClass::myFunction, this };
The myFunction() method does not take any parameters here as arguments, but when the first parameter to std::thread's constructor is a class method, and not a function, the first parameter is taken to be a pointer to an instance of the class whose method gets invoked, with the remaining parameters getting forwarded as usual.
But you will need to figure out, on your own, which class's instance you are trying to invoke, whether this, or some other instance of your class.
Although you can often write foo() inside a class to invoke this->foo(), as a shortcut, this is not the case when you're outright "naming" the member function, and that's what you're doing here as you are actually passing a member function pointer to std::thread.
It can work, you just need to supply the object pointer too:
std::thread t0(myFunction, this);
You could pass a pointer to a different myClass instead, if you liked!

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

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.

Error "member function redeclaration not allowed" with boost::thread

I have this problem with boost::thread that i cannot solve.
I have a classX.h file:
#include <boost/thread/thread.hpp>
class classX{
...
void startWork(void);
void doWork(void);
...
}
and then a .cpp file:
...
void classX::startWork(){
boost::thread(&doWork);
}
void classX::doWork(){
...
}
I cannot compile, i obtein the error (at the line in which i do boost::thread(&doWork)):
error C2761: 'void plsa_mt_2::doWork(void)' : member function redeclaration not allowed
Is this error related with the thread creation or with something else? What can i do to solve it?
Since classX::doWork() is a member function of classX, you can't call the member function pointer (&classX::doWork) without providing a pointer to a classX.
The Boostiest way to accomplish this is by using Boost Bind to create a callable functor with the member function pointer and a pointer to the classX, like so:
void classX::startWork() {
boost::thread t(boost::bind(&classX::doWork, this)); // be careful, the boost::thread will be destroyed when this function returns
}
You could alternatively make doWork() a static member function or a global function if doWork() doesn't need access to instance properties of the classX:
firstly, the correct syntax for getting a pointer to a member function is
&classX::doWork
However I tink you might not be showing the exact code yielding the error, because the typical error for &doWork in VS is
error C2276: '&' : illegal operation on bound member function expression

how to call a thread member function from main ( )

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".