#include <iostream>
#include <future>
#include <thread>
void set_value(std::promise<int>& prom) {
try {
// 模拟一些工作
std::this_thread::sleep_for(std::chrono::seconds(1));
int value = 42;
prom.set_value(value); // 设置 promise 的值
} catch (...) {
prom.set_exception(std::current_exception()); // 如果有异常,设置 promise 的异常
}
}
int main() {
std::promise<int> prom;
std::future<int> fut = prom.get_future(); // 获取与 promise 关联的 future
std::thread th(set_value, std::ref(prom));
try {
int value = fut.get(); // 等待并获取 promise 的值
std::cout << "Value: " << value << std::endl;
} catch (const std::exception& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
th.join();
return 0;
}
std::promise<T>:用于存储一个将来会被设置的值或异常。它可以与 std::future 配合使用,std::future 用于获取这个值或异常。std::future<T>:表示一个将来会可用的值或异常。它可以从 std::promise 或其他异步操作中获取结果。set_value():在另一个线程中模拟一些工作,并通过 prom.set_value(value) 将结果设置到 promise 中。fut.get():主线程等待 promise 的值被设置,并获取该值。如果 promise 中设置了异常,则 get() 会抛出该异常。set_value() 函数中抛出异常,可以通过 prom.set_exception(std::current_exception()) 将异常传递给 future。这段代码展示了如何使用 std::promise 和 std::future 进行线程间的通信和同步。
上一篇:c++类型强制转换
下一篇:c++输出字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站