4

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.

Community
  • 1
  • 1
MrJonas
  • 197
  • 11

2 Answers2

5

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.

sehe
  • 374,641
  • 47
  • 450
  • 633
4

You need to pass a function pointer and the object instance as separate arguments to the thread constructor:

std::thread t1(&myClass::myFun, &myObj);

This will cause the myFun member function being called, with its first argument being a pointer to the myObj instance, just like member functions wants it.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621