C++ future 的第一课:先理解那个共享状态 — Hacker News 中文摘要
来源:devblogs.microsoft.com — 31 分
📋 概述
Raymond Chen 拆解 C++ 标准库里的 std::promise、std::packaged_task、std::async、std::future 与 std::shared_future:它们全部建立在标准里那个匿名的“state”之上,他把它叫 source,因为那是真正产出值的地方,行为类似 C# 的 task completion source。文章给出简化实现,用判别式、union、mutex 与条件变量把“设值、设异常、取值”三件事串起来。
🔑 核心要点
- source 支持的操作是设值、设异常、取值或重抛异常。
- 判别式区分四种状态:空、有值、有异常、已被取走。
- 重复设值会抛 std::future_error(future_errc::promise_already_satisfied)。
- mutex 保证线程安全,条件变量负责等待别人设值或设异常。
- 理解这层共享状态后,五个类的差异只剩下“谁来写、谁能读、能不能复制”。
💡 金句
The idea is that all of these classes are built of a single unnamed class which the C++ standard library calls the state.
👍 0
👎 0
← 返回 Hacker News 首页