Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling an objects member function in a thread in main() [duplicate]

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.

like image 231
MrJonas Avatar asked Jan 11 '23 13:01

MrJonas


1 Answers

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.

like image 146
sehe Avatar answered Jan 30 '23 12:01

sehe