jeudi 26 mars 2020

Why is it so difficult to have a thread inside a class in c++ and invoke it with a constructor?

I have been trying to invoke threads from class constructors to no avail. Why is it so hard to pass a function or object to a thread.

#include <iostream>
#include <thread>
class a{
        public:
        a();
        std::thread t;
        int data;
        //virtual void fn();
};

void fn(a *p)
{
        std::cout << "Thread Function : " << p->data << std::endl;
}

a::a():data(10)
//a::a():data(10),t(fn,this)
{

        void (*fnp)(a *p) = fn;
        fn(this);
        fnp(this);
        t(fnp, this);
}

int main ()
{
        a av;
        return 0;
}

Its output looks as:

preetam@preetam-GL702ZC:~/Desktop$ g++ v.cpp -lpthread
v.cpp: In constructor ‘a::a()’:
v.cpp:23:13: error: no match for call to ‘(std::thread) (void (*&)(a*), a*)’
  t(fnp, this);

All I want is to start a thread from the constructor and have that thread access the class members with ease.

Aucun commentaire:

Enregistrer un commentaire