知识卡片

支付系统案例卡 · 6074.e.1.b.3.a

并发取款在检查后交错透支

理解等级:中级

多个取款线程都先检查余额,随后才扣减,可能同时依据旧余额通过检查并造成透支。示例用sleep增加交错机会,真实问题不需要人为延时。C++未同步读写本身还有数据竞争与未定义行为,不能保证只出现某个负数。对应方案见[[余额检查扣减保持同一临界区]]。

这张卡片看不懂?

已有反馈 · 0 / 10 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Chapter 3. Concepts Data races in C++ · 查看原书依据

      What if another thread changes `balance_` at this point? std::this_thread::sleep_for(std::chrono::milliseconds(500)); balance_ -= amount; return true; } private: int64_t balance_; }; This example is in C++, not Rust, for reasons that will become clear shortly. However, the same general concepts apply in many other (non-Rust) languages—Java, or Go, or Python,

    参考来源

    - 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第3章《Data races in C++》(spine7;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch03.html;u101-ch03-032)。 - 结论依据:原文在“What if another thread”附近的定义、例子或代码支撑本卡核心说明:多个取款线程都先检查余额,随后才扣减,可能同时依据旧余额通过检查并造成透支。边界按已读前提解释;示例未执行。 - 原始内容:What if another thread changes `balance_` at this point? std::this_thread::sleep_for(std::chrono::milliseconds(500)); balance_ -= amount; return true; } private: int64_t balance_; }; This example is in C++, not Rust, for reasons that will become clear shortly. However, the same general concepts apply in many other (non-Rust) languages—Java, or Go, or Python,