yewei
yewei

Reputation: 241

is there some method to make one function in c++'s class to run in different thread

if I have one class, is there some method to generate a second thread and call another function? the below is my testing, but cannot work.

#include <iostream>
#include <thread>

class A
{
public:
    void print_A();
    void print_B();
};

void A::print_A()
{
     std::cout << "in print_A and now need to create another thread and in this thread call print_B" << std::endl;
     std::thread t1(&A::print_B);
     t1.join;
}

void A::print_B()
{
     std::cout << "print_B" << std::endl;
}

int main()
{
    A a;
    a.print_A();
    return 0;
}

Upvotes: 0

Views: 64

Answers (2)

The Apache
The Apache

Reputation: 1074

Well..you can do something like this..

#include <iostream>
#include <thread>

class A 
{ 
   public:
    void print_A(); 
    void print_B(); 
};

void A::print_A()
{ 
  std::cout << "in print_A and now need to create another thread and in this       thread call print_B" << std::endl;

  //the changes needed
  std::thread t1(&A::print_B, this);
  t1.join();
 }

void A::print_B() { std::cout << "print_B" << std::endl; } 

int main() { A a; a.print_A(); return 0; }

Note: Corrected a typo

Upvotes: 1

simpel01
simpel01

Reputation: 1782

You should use std::async:

#include <future>
void A::first_fun()
{
   auto future = std::async(&A::second_fun, this);
   return future.get();
}

Note that future.get() will block waiting for the thread to complete.

if instead you want to wait for its completion later in the code then you can return the future object and call the .get() method later.

Upvotes: 6

Related Questions