跳转到内容
主菜单
主菜单
移至侧栏
隐藏
导航
首页
最近更改
随机页面
MediaWiki帮助
代码酷
搜索
搜索
中文(中国大陆)
外观
创建账号
登录
个人工具
创建账号
登录
未登录编辑者的页面
了解详情
贡献
讨论
编辑“︁
C++ 异步任务
”︁
页面
讨论
大陆简体
阅读
编辑
编辑源代码
查看历史
工具
工具
移至侧栏
隐藏
操作
阅读
编辑
编辑源代码
查看历史
常规
链入页面
相关更改
特殊页面
页面信息
外观
移至侧栏
隐藏
您的更改会在有权核准的用户核准后向读者展示。
警告:
您没有登录。如果您进行任何编辑,您的IP地址会公开展示。如果您
登录
或
创建账号
,您的编辑会以您的用户名署名,此外还有其他益处。
反垃圾检查。
不要
加入这个!
{{DISPLAYTITLE:C++异步任务}} '''C++异步任务'''是C++多线程编程中的重要概念,通过`<future>`和`<thread>`等头文件提供的工具,允许开发者以非阻塞方式执行任务并获取结果。本页详细介绍其核心组件、使用方法和实际应用场景。 == 概述 == 异步任务(Asynchronous Task)允许程序在后台执行耗时操作(如计算、I/O),同时主线程继续处理其他任务。C++11引入的`std::async`、`std::future`和`std::promise`为此提供了标准化支持。 关键优势包括: * '''非阻塞执行''':主线程无需等待任务完成。 * '''结果获取''':通过`future`对象延迟获取返回值或异常。 * '''资源管理''':自动处理线程生命周期。 == 核心组件 == === std::async === 启动异步任务,返回`std::future`对象。语法: <syntaxhighlight lang="cpp"> #include <future> #include <iostream> int compute() { return 42; // 模拟耗时计算 } int main() { std::future<int> result = std::async(std::launch::async, compute); std::cout << "Main thread continues..." << std::endl; std::cout << "Result: " << result.get() << std::endl; // 阻塞直至结果就绪 return 0; } </syntaxhighlight> 输出: <pre> Main thread continues... Result: 42 </pre> 参数`std::launch::async`强制创建新线程,而`std::launch::deferred`延迟执行(调用`get()`时运行)。 === std::future === 表示异步操作的结果,提供以下方法: * `get()`:获取结果(若未就绪则阻塞)。 * `wait()`:等待结果就绪。 * `valid()`:检查结果是否可用。 === std::promise === 允许显式设置值或异常,与`std::future`配对使用: <syntaxhighlight lang="cpp"> void set_value(std::promise<int>&& prom) { prom.set_value(100); } int main() { std::promise<int> prom; std::future<int> fut = prom.get_future(); std::thread t(set_value, std::move(prom)); std::cout << "Future value: " << fut.get() << std::endl; t.join(); return 0; } </syntaxhighlight> == 实际案例 == === 并行计算 === 计算两个向量的点积,分解为多个异步任务: <syntaxhighlight lang="cpp"> #include <vector> #include <numeric> #include <future> double dot_product(const std::vector<double>& a, const std::vector<double>& b, size_t start, size_t end) { return std::inner_product(a.begin() + start, a.begin() + end, b.begin() + start, 0.0); } int main() { std::vector<double> a(1000, 1.0), b(1000, 2.0); auto fut1 = std::async(std::launch::async, dot_product, std::ref(a), std::ref(b), 0, 500); auto fut2 = std::async(std::launch::async, dot_product, std::ref(a), std::ref(b), 500, 1000); double result = fut1.get() + fut2.get(); std::cout << "Dot product: " << result << std::endl; // 输出 2000 } </syntaxhighlight> === 超时处理 === 使用`std::future::wait_for`实现超时控制: <syntaxhighlight lang="cpp"> std::future<int> fut = std::async([](){ std::this_thread::sleep_for(std::chrono::seconds(5)); return 123; }); if (fut.wait_for(std::chrono::seconds(2)) == std::future_status::timeout) { std::cout << "Task timeout\n"; } else { std::cout << "Result: " << fut.get() << "\n"; } </syntaxhighlight> == 进阶主题 == === 异常传递 === 异步任务中的异常会通过`future::get()`重新抛出: <syntaxhighlight lang="cpp"> auto fut = std::async([](){ throw std::runtime_error("Error in async task"); }); try { fut.get(); } catch (const std::exception& e) { std::cerr << "Caught: " << e.what() << std::endl; } </syntaxhighlight> === 线程池集成 === 结合自定义线程池优化资源使用(伪代码): <syntaxhighlight lang="cpp"> ThreadPool pool(4); // 4个工作线程 auto fut = pool.enqueue([](){ return /* ... */; }); </syntaxhighlight> == 性能考虑 == * 频繁创建线程的开销较大,建议复用线程(如线程池)。 * `std::async`默认策略由实现决定,显式指定`std::launch::async`或`deferred`以避免歧义。 == 总结 == C++异步任务简化了多线程编程,适合I/O密集型或可并行计算场景。通过`future`/`promise`模型,开发者可以高效管理任务依赖和结果同步。 <mermaid> graph LR A[主线程] --> B[启动异步任务] B --> C[std::async] C --> D[返回 std::future] D --> E[主线程继续执行] E --> F[调用 future.get()] F --> G[阻塞/获取结果] </mermaid> [[Category:编程语言]] [[Category:C++]] [[Category:C++ 多线程]]
摘要:
请注意,所有对代码酷的贡献均被视为依照知识共享署名-非商业性使用-相同方式共享发表(详情请见
代码酷:著作权
)。如果您不希望您的文字作品被随意编辑和分发传播,请不要在此提交。
您同时也向我们承诺,您提交的内容为您自己所创作,或是复制自公共领域或类似自由来源。
未经许可,请勿提交受著作权保护的作品!
取消
编辑帮助
(在新窗口中打开)