我正在尝试将方法作为新线程调用,并将该方法返回的值分配给变量。
EG:
int numObjects = thread t7(methodName(parameter));
我该如何去做呢?
我确信我错过了一些简单的东西,但这让我很困惑。
提前致谢
最佳答案
您需要使用 std::future
与 std::async
结合.
std::future<int> fut = std::async(methondname, parameter);
// do something
// will wait for the result to become available
std::cout << fut.get() << std::endl;
我还建议阅读我链接到的 std::async
文档,因为有不同的启动策略,例如:它真的在单独的线程中运行还是延迟执行。
另一种可能性是简单地将输出参数(通过 std::ref
)与 std::thread
一起使用,但是您必须手动加入并且也不要无法获得继承于 std::async
的异常安全性。所以你最好坚持使用std::async
。
关于c++ - 在新线程中调用方法并将返回值分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25259519/