std::future与std::promise在C++多线程同步与数据共享中的应用
1、std::promise与std::future
std::promise与std::future通过配合使用完成数据的同步与共享,两者均是模板类;std::promise存储异步执行的值或异常;std::future提供可供访问的异步执行结果。二者配合使用伪码如下:
std::promise<Type> pr;
std::future<Type> fu(pr.get_future());
2、基础示例代码
#include <iostream> #include <thread> #include <future> void promise_string(std::promise<std::string> &pr) { try { std::string str = __func__; pr.set_value(str); } catch (const std::exception& e) { pr.set_exception(std::current_exception()); } } int main() { std::promise<std::string> pr; std::future<std::string> fu(pr.get_future()); std::thread tr(&promise_string, ref(pr)); std::cout << "the current thread function name is:" << fu.get().c_str() << std::endl; tr.join(); system("pause"); }
注意:上述代码中,fu.get()获取结果是阻塞的,在异步操作未执行完时,fu.get()将阻塞主线程直到异步操作完成。
3、不同线程间数据的传递
#include <iostream> #include <thread> #include <future> void promise_string(std::promise<std::string> &pr) { try { for (int i = 0; i < 100; i++) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); std::cout << "sleep" << std::endl; } std::string str = __func__; pr.set_value(str); } catch (const std::exception& e) { pr.set_exception(std::current_exception()); } } void print_promise_info(std::future<std::string> &fu) { std::cout << "the promise thread function name is: " << fu.get().c_str() << std::endl; std::cout << "the current thread function name is: " << __FUNCTION__ << std::endl; } int main() { std::promise<std::string> pr; std::future<std::string> fu(pr.get_future()); std::thread tr(&promise_string, ref(pr)); std::thread trp(&print_promise_info,ref(fu)); tr.detach(); trp.detach(); system("pause"); }
promise_string在一个线程tr中计算string值,trp线程启动并在fu.get()处阻塞直到线程tr执行完毕,线程tr执行完毕后,线程trp继续执行其他功能代码。
又没有什么可说的
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现