是否有某种方法可以使C ++类中的一个函数在不同的线程中运行

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

本文关键字:函数 一个 运行 线程 可以使 方法 是否      更新时间:2023-10-16

如果我有一个类,是否有一些方法可以生成第二个线程并调用另一个函数?以下是我的测试,但无法工作。

#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;
}

您应该使用std::async:

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

请注意,future.get()将阻止等待线程完成。

如果您希望稍后在代码中等待它的完成,则可以返回future对象并稍后调用.get()方法。

嗯。。你可以做这样的事。。

#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; }

注意:更正了一个打字错误

相关文章: