C ++ 11 multithreading with class function
I want to use multithreading in C ++ 11 to call a function of a class member on my own thread. I was able to get this to work with a global function:
#include <thread>
#include <iostream>
void Alpha(int x)
{
while (true)
{
std::cout << x << std::endl;
}
}
int main()
{
std::thread alpha_thread(Alpha, 5);
alpha_thread.join();
return 0;
}
However, I cannot compile it using the member function of the class:
#include <thread>
#include <iostream>
class Beta
{
public:
void Gamma(int y)
{
while (true)
{
std::cout << y << std::endl;
}
}
};
int main()
{
Beta my_beta;
std::thread gamma_thread(my_beta.Gamma, 5);
gamma_thread.join();
return 0;
}
Compilation error:
no matching function for call to 'std::thread::thread(<unresolved overloaded function type>)'
std::thread gamma_thread(my_beta.Gamma, 5);
^
What am I doing wrong?
+2
source to share
3 answers
You need to pass two things: a pointer to an element and an object. You cannot call a non-stationary member function (for example Gamma
) in C ++ without an object. The correct syntax is:
std::thread gamma_thread(&Beta::Gamma, // the pointer-to-member
my_beta, // the object, could also be a pointer
5); // the argument
You can think of my_beta
here as the first argument Gamma()
and 5
as the second.
+5
source to share
You have several problems with your program.
- As your compilation error says, you need to pass the address to the function
&Beta::Gamma
. - You need to pass the object as a parameter, assuming
this
an implicit parameter of the member function
Modified source
#include <thread>
#include <iostream>
class Beta
{
public:
void Gamma(int y)
{
while (true)
{
std::cout << y << std::endl;
}
}
};
int main()
{
Beta my_beta;
std::thread gamma_thread(&Beta::Gamma, my_beta, 5);
gamma_thread.join();
return 0;
}
+1
source to share