如果我有一个类,是否有一些方法可以生成第二个线程并调用另一个函数?以下是我的测试,但无法正常工作。
#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/