golang-design / under-the-hood

📚 Go: Under The Hood | Go 语言原本 | https://golang.design/under-the-hood

Home Page:https://golang.design/under-the-hood

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

map不能用cas更新value

flippedme opened this issue · comments

实际描述

  • 文件路径:under-the-hood/gosrc/sync/map.go
  • 原文段落:L69
// 一个 entry 可以被原子替换为 nil 来删除:当 m.dirty 是下一个创建的,它会自动将 nil 替换为 expunged 且
// 让 m.dirty[key] 成为未设置的状态。

预期描述

// 一个 entry的p字段 可以被原子替换为 nil 来删除:当 m.dirty 是下一个创建的,它会自动将 nil 替换为 expunged 且
// 让 m.dirty[key] 成为未设置的状态。

PR welcome

@changkun Is there a way to get the pointer of a value stored in the map, and use CAS to change that? suddenly curious

@flippedme I don't fully understand your question. Could you please add an example that explains more of your curiosity?

@changkun Well, for example in an object

type People struct{ age int32 }
p := People{}
atomic.CompareAndSwapInt32(&p.age, 30, 35)

and I wondered wether we can do the same thing to a map, you know, get-the-address-cas-change pattern.
But I figured that the address is not always valid because of map growth or shrink.
thanks

@flippedme Aha. Indeed. Sadly, you can't. map access is not concurrent safe, this is well known.