Pass the member function of the class to thread

#include <iostream>
#include <thread>
using namespace std;

class love{
public:
    void saylove(string name);
    static void sayloveyou();
};

void love::saylove(string name){
    cout<<"I love "<<name<<"!"<<endl;
}

void love::sayloveyou(){
    cout<<"I love you!"<<endl;
}

int main(){
    love loveadapter;
    thread t0(&love::sayloveyou);
    t0.join();
    thread t1(&love::saylove, loveadapter, "one");//The object can be passed
    t1.join();
    thread t2(&love::saylove, &loveadapter, "two");//Pass pointers
    t2.join();
    thread t3(bind(&love::saylove, loveadapter, "three"));//The object can be passed in bind
    t3.join();
    thread t4(bind(&love::saylove, &loveadapter, "four"));//Pass pointers in bind
    t4.join();
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325859387&siteId=291194637