0

There is a topic about Start thread with member function

And this is one given example:

#include <thread>
#include <iostream>

class bar {
public:
    void foo() {
        std::cout << "hello from member function" << std::endl;
    }
};

int main()
{
   std::thread t(&bar::foo, bar());
   t.join();
}

But now the problem is I need to use thread variable in different functions, so I will need to split codes into two parts which are std::thread t(&bar::foo, bar()); and t.join();

I use this below:

class A {
public:
    std::thread t;
    void foo();
    void use0();
    void use1();
}

A::foo()
{
}

A::use0()
{
    std::thread t(&A::foo);
}

A::use1()
{
    t.join();
}

And I get a error saying std::invoke : No match was found for the overloaded function.

What should I do? Thanks a lot!

Community
  • 1
  • 1
Panfeng Li
  • 3,321
  • 3
  • 26
  • 34

1 Answers1

1
  1. To execute a non-static member function in another thread, you need to pass the instance of your class, too:

    std::thread t(&A::foo, this);
    
  2. You're creating a local std::thread in use0 (and you're not calling std::thread::join before its destruction). Assign to the member t instead:

    t = std::thread(&A::foo, this);
    
  3. You're missing a semicolon after class definition and the return types (voids) in your member function definitions.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74