推荐答案
// www.javascriptcn.com code example
#include <iostream>
#include <future>
#include <thread>
void task(std::promise<int>&& prom) {
// 模拟一些耗时操作
std::this_thread::sleep_for(std::chrono::seconds(2));
prom.set_value(42); // 设置 promise 的值
}
int main() {
std::promise<int> prom;
std::future<int> fut = prom.get_future(); // 获取与 promise 关联的 future
std::thread t(task, std::move(prom)); // 启动线程执行任务
std::cout << "Waiting for the result..." << std::endl;
int result = fut.get(); // 阻塞等待 future 的结果
std::cout << "Result: " << result << std::endl;
t.join(); // 等待线程结束
return 0;
}本题详细解读
std::promise 和 std::future 的作用
std::promise 和 std::future 是 C++11 引入的用于线程间通信的工具。它们通常用于在一个线程中设置一个值,并在另一个线程中获取该值。
- std::promise: 用于存储一个值或异常,并允许在稍后的时间点通过
std::future获取该值。 - std::future: 用于获取与
std::promise关联的值或异常。它提供了一种异步获取结果的机制。
代码解析
创建 promise 和 future:
std::promise<int> prom;创建一个promise对象,用于存储一个int类型的值。std::future<int> fut = prom.get_future();获取与promise关联的future对象,用于在稍后获取promise中存储的值。
启动线程执行任务:
std::thread t(task, std::move(prom));启动一个新线程,并将promise对象传递给任务函数task。std::move(prom)用于将promise对象的所有权转移给线程。
任务函数:
- 在
task函数中,模拟了一些耗时操作(如std::this_thread::sleep_for),然后通过prom.set_value(42);设置promise的值为42。
- 在
获取结果:
- 在主线程中,
int result = fut.get();阻塞等待future的结果,直到promise中的值被设置。一旦promise的值被设置,future就会返回该值。
- 在主线程中,
线程同步:
t.join();确保主线程等待任务线程完成后再继续执行。
使用场景
std::promise 和 std::future 通常用于以下场景:
- 异步任务的返回值传递。
- 线程间的同步和数据传递。
- 实现类似于回调的机制,但更加灵活和类型安全。
注意事项
std::future的get()方法只能调用一次,调用后future对象将变为无效。std::promise和std::future是线程安全的,可以在多线程环境中安全使用。- 如果
promise在未设置值的情况下被销毁,future的get()方法将抛出std::future_error异常。