Call a method of class inside a thread in C++

馋奶兔 提交于 2020-01-30 08:55:26

问题


How can I call a method of class inside a thread? I have a simple method of class and a simple thread... How can I execute de method inside a Thread? Follow the code...

#include <iostream>
#include<thread>

using namespace std;

class Airplaine{
      public:

      int vel = 0;

      void impress(){ cout << "my impress";} // meu método
};

int main(){

        Airplaine *av1=new Airplaine();

       thread first(meu_method_impress()_here); // my method impress inside a thread

       first.detach();

      return 0;
}

回答1:


To compliment the answer of @Pete, you can bind the member function and feed your thread just like a normal function which accepts the object as its argument.

Airplaine* av1 = new Airplaine;
std::function<void(Airplaine*)> func = std::bind(&Airplaine::impress, std::placeholders::_1);
std::thread first(func, av1);
first.join();

functional header is needed.

Or you can use a lambda function:

auto f = [](Airplaine* av) {av->impress(); };
std::thread first(f, av1);



回答2:


The thread constructor is pretty smart. Just tell it which member function to call and give it an object to call the function on:

Airplane *av1 = new Airplane;
std::thread first(&Airplane::impress, av1);
first.join(); // wait for thread to finish

Or, in a more C++-like style:

Airplane av;
std::thread first(&Airplane::impress, av);
first.join(); // wait for thread to finish

Or, if the member function modifies the object and you need to see those modifications after the thread finishes, pass the object by reference:

Airplane av;
std::thread first(&Airplane::impress, std::ref(av));
first.join(); // wait for thread to finish


来源:https://stackoverflow.com/questions/56300636/call-a-method-of-class-inside-a-thread-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!