I'm trying to work out why I have a data race problem (on go 1.15 and 1.16).

*SearchResults.Set is called from several goroutines. I am trying to avoid
concurrent access to its two maps using a mutex, but this isn't working.

108 type SearchResults struct {
109     Boxes map[string][]Box
110     seen  map[string]bool
111     sync.Mutex
112 }
113
114 // Set adds a new box to the search results map
115 func (s *SearchResults) Set(b Box) {
116
117     s.Lock()
118     defer s.Unlock()
119
120     if _, ok := s.seen[b.BoxID]; ok { // race problem
121         return
122     }
123
124     if model := b.GetModel(); model != "" {
125         s.Boxes[model] = append(s.Boxes[model], b) // race problem
126         s.seen[b.BoxID] = true // race problem
127     }
128 }

The data race report from go run -race <program> shows

==================
WARNING: DATA RACE
Write at 0x00c000012e70 by goroutine 16:
  runtime.mapassign_faststr()
      /home/rory/bin/go/src/runtime/map_faststr.go:202 +0x0
  main.(*SearchResults).Set()
      /home/rory/src/go-cex/cexer.go:126 +0x345
...
Previous read at 0x00c000012e70 by goroutine 8:
  runtime.mapaccess2_faststr()
      /home/rory/bin/go/src/runtime/map_faststr.go:107 +0x0
  main.(*SearchResults).Set()
      /home/rory/src/go-cex/cexer.go:120 +0xf6
...
==================
WARNING: DATA RACE
Read at 0x00c000012ea0 by goroutine 8:
  runtime.mapaccess1_faststr()
      /home/rory/bin/go/src/runtime/map_faststr.go:12 +0x0
  main.(*SearchResults).Set()
      /home/rory/src/go-cex/cexer.go:125 +0x195
...
Previous write at 0x00c000012ea0 by goroutine 16:
  runtime.mapassign_faststr()
      /home/rory/bin/go/src/runtime/map_faststr.go:202 +0x0
  main.(*SearchResults).Set()
      /home/rory/src/go-cex/cexer.go:125 +0x2a7
...

Advice gratefully received.

Rory

-- 
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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAPQX7QR1Evk7BzKAxwq3GKH%3DgiNb4YVs_ap7Q%2BUVC_OByoty2w%40mail.gmail.com.

Reply via email to