maciekkov
maciekkov

Reputation: 23

Thread inside a class with member function from another class

Can someone tell me how can I run a new thread with member function from a object of diffrent class as a member function of this class ? What ever im trying to do Im still getting errors.

no match for call to '(std::thread) (void (Boo::*)(), Boo&)'|
no match for call to '(std::thread) (void (Foo::*)(), Foo*)'|

#include <iostream>
#include <thread>
using namespace std;
class Boo
{
public:
    void run()
    {
        while(1){}
    }
};

class Foo
{
public:
    void run()
    {
        t1(&Boo::run,boo);
        t2(&Foo::user,this);
    }
    void user();
    ~Foo(){
        t1.join();
        t2.join();
    }
private:
    std::thread t1;
    std::thread t2;
    Boo boo;
};
int main()
{
    Foo foo;
    foo.run();
}

Upvotes: 2

Views: 4067

Answers (1)

Steve Lorimer
Steve Lorimer

Reputation: 28659

You need to use operator= to assign the threads after construction

Working example below (see it in action):

#include <thread>
#include <iostream>

class Boo
{
public:
    void run()
    {
        int i = 10;
        while(i--)
        {
            std::cout << "boo\n";;
        }
    }
};

class Foo
{
public:
    void run()
    {
        t1 = std::thread(&Boo::run,boo);   // threads already default constructed
        t2 = std::thread(&Foo::user,this); // so need to *assign* them 
    }

    void user()
    {
        int i = 10;
        while(i--)
        {
            std::cout << "foo\n";;
        }
    }

    ~Foo()
    {
        t1.join();
        t2.join();
    }

private:
    std::thread t1;
    std::thread t2;
    Boo boo;
};

int main()
{
    Foo foo;
    foo.run();
}

Upvotes: 5

Related Questions