std::future和std::promise用于线程间安全传递结果,promise设置值或异常,future获取该值,二者通过共享状态关联,实现无需锁的异步通信。

在C++中,std::future 和 std::promise 是标准库提供的用于线程间传递值的机制。它们配合使用可以实现一个线程计算结果,另一个线程获取该结果,而无需手动加锁或共享变量。
std::promise 是一个可写入一次的对象,用来设置某个值或异常;std::future 是其对应的只读句柄,用来获取这个值。两者通过共享状态关联。
下面是一个典型的用法:创建一个线程执行任务,并通过 promise 返回结果。
#include <iostream>
#include <thread>
#include <future>
<p>void compute(std::promise<int>&& result) {
int value = 42 * 2; // 模拟耗时计算
result.set_value(value); // 设置结果
}</p><p>int main() {
std::promise<int> prom;
std::future<int> fut = prom.get_future(); // 获取关联的 future</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">std::thread t(compute, std::move(prom));
std::cout << "等待结果...\n";
int result = fut.get(); // 阻塞,直到值被设置
std::cout << "得到结果: " << result << "\n";
t.join();
return 0;}
输出:
立即学习“C++免费学习笔记(深入)”;
等待结果... 得到结果: 84
除了正常值,promise 还能传递异常,让 future 能捕获到。
void task_with_exception(std::promise<double>&& p) {
try {
throw std::runtime_error("出错了!");
} catch (...) {
p.set_exception(std::current_exception());
}
}
<p>int main() {
std::promise<double> p;
std::future<double> f = p.get_future();</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">std::thread t(task_with_exception, std::move(p));
try {
double val = f.get(); // 这里会重新抛出异常
} catch (const std::exception& e) {
std::cout << "捕获异常: " << e.what() << "\n";
}
t.join();
return 0;}
set_value、set_exception 或 set_value_at_thread_exit,多次调用会抛出异常std::future_error
基本上就这些。std::future 和 std::promise 提供了一种安全、简洁的线程通信方式,避免了直接操作共享数据的风险,适合一对一线程结果传递场景。
以上就是c++++怎么使用std::future和std::promise进行线程通信_c++ future与promise线程通信机制的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号