c++ - 是否有一些方法可以使 c++ 类中的一个函数在不同的线程中运行

标签 c++ multithreading

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

#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() 方法。

关于c++ - 是否有一些方法可以使 c++ 类中的一个函数在不同的线程中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33910189/

相关文章:

c++ - 返回浮点类型是否完全符合 IEEE-754 的函数?

c++ - std::istream 提取运算符( double 或 float )在 VS 2012 中非常慢

java - 可以恢复线程但无法完全停止

multithreading - 使用线程复制主线程添加到字符串列表的文件

c++ - 如何打印 QStringListModel 内容?

c++ - Xerces-c断言错误

c++ - 具有运算符重载的 accumulate()

c++ - 为什么这段代码中调用了两次析构函数?

java - 在应用程序中实现同步和异步行为的有效方法

c++ - std::atomic 在一个简单的 POD 类上