vendredi 13 décembre 2019

How to use a thread member in a class, to invoke a method/ function in c++

I want to invoke a function via thread that thread is a member of a class, But i can execute it as it tells "Invalid use of non static member function th = std::thread(fn, obj);" can some one tell whether is it possible to use thread as a member of class, if so how to use it?

#include<iostream>
#include<thread> 

class Mover
{
public:
    void teleport(){
        std::cout << "teleport called\n";
    }
};

class Transmit
{
private:
    std::thread th;
public:
    void fn(Mover obj);
    Transmit(Mover obj);
};

//Constructor
Transmit::Transmit(Mover obj)
{
    th = std::thread(fn, obj);  //Is it possible?
}
//Destructor
Transmit::~Transmit(){
    if(th.joinable())
        th.join();
}

void Transmit::fn(Mover obj)
{
    while(1){
        obj.teleport();
    }
}

int main(){
    Mover obj;
    Tansmit tm(obj);
    return 0;
}

Thanks

Aucun commentaire:

Enregistrer un commentaire