std::future和std::promise用于线程间传递数据,promise设置一次结果,future获取该结果并支持异常传递,需注意只能设置一次且get后失效。

在C++中,std::future 和 std::promise 是用于线程间传递数据的重要工具。它们配合使用,可以实现一个线程计算结果,另一个线程获取结果的功能。
std::promise 是一个可写入一次的对象,用来保存某个值或异常。每个 promise 与一个共享状态相关联,可以通过它设置结果。
std::future 是一个只读对象,用来获取 promise 设置的结果。它可以等待结果就绪,并通过 get() 方法取出值。
下面是一个简单的例子,展示如何在一个线程中通过 promise 设置值,在主线程中通过 future 获取:
#include <iostream>
#include <thread>
#include <future>
void setValue(std::promise<int>&& p) {
std::this_thread::sleep_for(std::chrono::seconds(2));
p.set_value(42); // 设置结果
}
int main() {
std::promise<int> prms;
std::future<int> fut = prms.get_future(); // 获取对应的 future
std::thread t(setValue, std::move(prms));
std::cout << "等待结果...\n";
int value = fut.get(); // 阻塞直到结果可用
std::cout << "得到结果: " << value << "\n";
t.join();
return 0;
}
除了正常值,promise 还可以设置异常,future 在 get() 时会抛出该异常:
void setException(std::promise<int>&& p) {
try {
throw std::runtime_error("出错了!");
} catch (...) {
p.set_exception(std::current_exception());
}
}
调用 fut.get() 时会重新抛出这个异常,需用 try-catch 捕获。
立即学习“C++免费学习笔记(深入)”;
以上就是c++++怎么使用std::future和std::promise_c++ std::future与std::promise使用方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号