dimanche 6 décembre 2015

Calling a member function on a separate thread via a pointer to the class

I am trying to invoke a function which accepts no parameters through a pointer from pointer which is a member of a different class on a thread other than the main thread.

Heres the code :-

#include <iostream>
#include <thread>

class client;

class base  {
public:
    base();
    virtual void func1(int param1) = 0;
    virtual void func2(int param1) = 0;
    client* link_ptr;
};

class client    {
public:
    client(base*);
    void foo()  {
        std::cout<<"Inside foo Function "<<std::endl;;
    }
private:
    base* mPtr;
};

client::client(base* ptr) : mPtr(ptr) {};

base::base()    {
    link_ptr = new client(this);
}

class derieved_level1   :   public virtual base {
public:
    virtual void func1(int param1) = 0;
    virtual void func2(int param1) = 0;
protected:
    std::string name;
};

struct derieved_level2 : public virtual derieved_level1 {
    derieved_level2()   {
        std::cout<<"level2 constructor"<<std::endl;
    }
    void func1(int param1)  {
        std::cout<<"func1 in level2 param="<<param1<<std::endl;
    }
    void func2(int param1)  {
        std::cout<<"func1 in level2 param="<<param1<<std::endl;
    }
};


int main()  {
    std::cout<<"Hello World!"<<std::endl;
    base* base_ptr = new derieved_level2();
    std::thread th1 (&client::foo,base_ptr->link_ptr);
    if (th1.joinable())
        th1.join();
    return 0;
}

The code compiles but exits with the following output :-

Hello World!
level2 constructor
libc++abi.dylib: terminating
Abort trap: 6

Invoking the function alone in the main() works fine. Is it possible to call it in a different thread ?

My approach to the problem might not be optimal. I am relatively new to the multithreading aspects of the language. Any suggestion is welcome.

Aucun commentaire:

Enregistrer un commentaire