On Thu, Sep 15, 2016 at 8:47 AM, sqweek E. <sqw...@gmail.com> wrote: > > Thanks everyone for helping me learn! If you'll humour me a moment longer, > I'm curious about the atomic.Value approach. If you have a single writer: > > newMap := make(map[int]int) > newMap[4] = 2 > newMap[9] = 3 > x.myMap.Store(newMap) //x.myMap is an atomic.Value > > And a reader: > > table := x.myMap.Load().(map[int]int) > fmt.Println(table[9]) > > Does go's memory model ensure that the read of table[9] sees the value the > writer put there (as long as the Load happens after the Store)?
Yes. (Well, Go's memory model doesn't actually discuss sync/atomic.Value at all. But, if it did, it would make this guarantee.) > If so, how does the compiler/runtime know that table[9] is a shared memory > location requiring properly publishing when it hasn't been explicitly > involved in any kind of barrier operation? Storing a value in a atomic.Value is a store-release operation, and loading a value from an atomic.Value is a load-acquire operation. That is, moving a value through atomic.Value ensures that all memory writes done by the writing goroutine preceding the atomic.Value are visible to the reading goroutine after reading from the atomic.Value. > If the writer/reader use a channel instead of atomic.Value, does it change > anything? ie. > > x.myMap = newMap //x.myMap is a map[int]int > x.changed <- nil > > <-x.changed > table := x.myMap > fmt.Println(table[9]) > > I guess in this case the scheduler could arrange for the reader to run on > the same processor as the writer did and avoid worrying about cache > inconsistencies? But I also see an opportunity here for the writer to update > the map again, after the reader has received on the channel but before it > has read from x.myMap. Which means the read could see the second update to > the map whose underlying hashtable may not be in a consistent state when > observed by the reader? It's the same answer: writing a value to a channel is a store-release, and reading a value is a load-acquire. Actually, channels might require an ever stronger guarantee of sequential consistency. I'm not sure off hand. Ian -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.