How to call class method within the thread?

Asked

Viewed 147 times

1

How do I call a class method inside a thread? I have a very simple thread and a class method. How do I call it inside the thread. As it is in the code below the compiler gives error

#include <iostream>
#include<thread>

using namespace std;

class Aviao{
    public:

        int vel = 0;

        void imprime(){ cout << "imressões";} // meu método
};

int main(){

    Aviao *av1=new Aviao();

    thread first(meu_método_imprime()_aqui); // meu método dentro da thread

    first.detach();
    return 0;
}
  • fix the indentation of your program...any slightly larger program without indentation is harder to understand...your program is very simple, you can understand, but there is practically no program in C or C++ (actually, in any language) that does not use any type of indentation

1 answer

1


You can use a lambda:

Aviao *av1 = new Aviao();

thread first([av1]{
    av1->imprime();
}); // meu método dentro da thread

Or alternatively use the bind function:

#include <functional>
...
thread second(std::bind(&Aviao::imprime, av1));
  • Thank you user72726

Browser other questions tagged

You are not signed in. Login or sign up in order to post.