知识卡片

问题卡 · 4545.g.8.d.2

分片锁不保护共享结果

理解等级:高级

原书Keys样例在多个goroutine中分别锁各自分片,再向同一个keys切片追加。各片数据虽受锁保护,公共结果切片仍被并发修改,因此存在竞态。应把每片结果先独立收集,再由单一汇总者合并,或另设保护结果的同步;等所有任务完成不能倒过来消除执行期间的竞态。

这张卡片看不懂?

已有反馈 · 0 / 10 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Cloud Native Patterns · 查看原书依据

      When you do need to establish locks on all of the tables, it’s generally best to do so concurrently. Below we implement a Keys function using goroutines and our old friend sync.WaitGroup. func (m ShardedMap) Keys() []string { keys := make([]string, 0) // Create an empty keys slice wg := sync.WaitGroup{} // Create a wait

    参考来源

    - 位置:《Cloud Native Go》第04章《Cloud Native Patterns》(来源项目book-sources;源文件:extracted/Cloud Native Go (Matthew A. Titmus)/_epub-src/OEBPS/ch04.xhtml) - 结论依据:原书Keys样例在多个goroutine中分别锁各自分片,再向同一个keys切片追加。原文相应定义、示例或限制为此结论提供依据;补充纠错与版本边界在正文就近标明。 - 原始内容:When you do need to establish locks on all of the tables, it’s generally best to do so concurrently. Below we implement a Keys function using goroutines and our old friend sync.WaitGroup. func (m ShardedMap) Keys() []string { keys := make([]string, 0) // Create an empty keys slice wg := sync.WaitGroup{} // Create a wait