I have found a lot about creating a new thread within a class (Passing member functions to std::thread)
But is it somehow possible to do the following:
#include <iostream>
#include <thread>
using namespace std;
class myClass
{
public:
myClass(){
myInt = 2;
};
void myFun(){
++myInt;
}
int ret_myInt(){
return myInt;
}
private:
int myInt;
};
int main ( void )
{
myClass myObj_;
std::thread t1( myObj_.myFun ); // (1)
t1.join();
cout << myObj_.ret_myInt() << endl;
return 0;
}
The Code is not working, because i cannot call a member function here (1). Is there a simple way to do that?
To be clear: I don't want to create the thread inside the member function.
You can use std::bind:
std::thread t1(std::bind(&myClass::myFun, std::ref(myObj_)));
Or you can use a lambda, or the variadics interface to the thread constructor.
std::thread t3([&myObj_]() { myObj_.myFun(); }); // lambda
std::thread t2(&myClass::myFun, std::ref(myObj_)); // variadics
It all comes down to the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With