文章目录
一、std::promise 和 std::future 的基本概念
在C++11中,std::promise 和 std::future 是用于实现异步编程的重要工具。它们提供了一种机制,允许一个线程将值或异常传递给另一个线程,从而实现线程间的数据传递和同步。
std::promise:
- 是一个模板类,用于存储一个值或异常
- 可以通过 set_value() 设置值,或者通过 set_exception() 设置异常
- 与 std::future 关联,用于将结果传递给其他线程。
std::future:
- 是一个模板类,用于从 std::promise 中获取值或异常。
- 可以通过 get() 方法获取结果。如果结果尚未准备好,get() 会阻塞当前线程,直到结果可用。
- 只能获取一次结果,调用 get() 后,future 的状态会变为无效。
二、std::promise 和 std::future 的基本使用
以下是一个简单的示例,展示如何使用 std::promise 和 std::future 在线程间传递数据:
#include <iostream>
#include <thread>
#include <future>
#include <chrono>
void task(std::promise<int> promise) {
std::this_thread::sleep_for(std::chrono::seconds(2)); // 模拟耗时操作
promise.set_value(42); // 设置结果
}
int main() {
std::promise<int> promise;
std::future<int> future = promise.get_future(); // 获取与 promise 关联的 future
std::thread t(task, std::move(promise)); // 启动线程,传递 promise
std::cout << "Waiting for result..." << std::endl;
int result = future.get(); // 阻塞等待结果
std::cout << "Result: " << result << std::endl;
t.join(); // 等待线程结束
return 0;
}
使用 std::promise 传递异常:
#include <iostream>
#include <thread>
#include <future>
#include <exception>
void task(std::promise<int> promise) {
try {
throw std::runtime_error("An error occurred!"); // 抛出异常
} catch (...) {
promise.set_exception(std::current_exception()); // 捕获并传递异常
}
}
int main() {
std::promise<int> promise;
std::future<int> future = promise.get_future();
std::thread t(task, std::move(promise));
try {
int result = future.get(); // 尝试获取结果
std::cout << "Result: " << result << std::endl;
} catch (const std::exception &e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
t.join();
return 0;
}
std::future 的其他用法
wait():
- 阻塞当前线程,直到结果可用。
- 不返回结果,仅用于同步。
wait_for() 和 wait_until():

最低0.47元/天 解锁文章
2226

被折叠的 条评论
为什么被折叠?



