2

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();
}
nwp
  • 9,623
  • 5
  • 38
  • 68
maciekkov
  • 23
  • 1
  • 3
  • `while(1){}` is UB, see for example [is-this-infinite-recursion-ub](https://stackoverflow.com/questions/5905155/is-this-infinite-recursion-ub). – Jarod42 Aug 30 '17 at 17:46

1 Answers1

4

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();
}
Steve Lorimer
  • 27,059
  • 17
  • 118
  • 213
  • His errors are because the run() and user() methods the threads call do not accept parameters, would your code not still have these errors? – Tyler Aug 30 '17 at 15:21
  • 1
    No, you're mistaken - the call he's trying to make is to execute the `run` **member function** of `Boo`, using the object `boo`. That is, you need both a member function pointer and an object instance – Steve Lorimer Aug 30 '17 at 15:22
  • Ok thanks, I misremembered the second parameter of the thread constructor. Deleted my incorrect answer – Tyler Aug 30 '17 at 15:24