title: Golang concurrent access map/array with fixed size
body: <p>I was exploring the possibility of concurrently accessing a map with fixed keys without a lock for performance improvement.
  I've explored the similar with slice before and seems it works:</p>
  
  <pre><code>func TestConcurrentSlice(t *testing.T) {
      fixed := []int{1, 2, 3}
      wg := &amp;sync.WaitGroup{}
      for i := 0; i &lt; len(fixed); i++ {
          idx := i
          wg.Add(1)
          go func() {
              defer wg.Done()
              fixed[idx]++
          }()
      }
      wg.Wait()
      fmt.Printf("%v\n", fixed)
  }
  </code></pre>
  
  <p>The above code will pass the -race test.</p>
  
  <p>That gave me the confidence of achieving the same thing with map with fixed size (fixed number of keys) because I assume if the number of keys doesn't change, so the underline array (in map) does not need to expand, so it will be safe for us to access different key (different memory location) in different go-routine. So I wrote this test:</p>
  
  <pre><code>type simpleStruct struct {
      val int
  }
  
  func TestConcurrentAccessMap(t *testing.T) {
      fixed := map[string]*simpleStruct{
          "a": {0},
          "b": {0},
      }
      wg := &amp;sync.WaitGroup{}
      // here I use array instead of iterating the map to avoid read access
      keys := []string{"a", "b"}
      for _, k := range keys {
          kcopy := k
          wg.Add(1)
          go func() {
              defer wg.Done()
              // this failed the race test
              fixed[kcopy] = &amp;simpleStruct{}
  
              // this actually can pass the race test!
              //fixed[kcopy].val++
          }()
      }
      wg.Wait()
  }
  </code></pre>
  
  <p>however, the test failed the race test with error message concurrent write by runtime.mapassign_faststr() function.</p>
  
  <p>And one more interesting I found is the code I've commented out "fixed[kcopy].val++" actually passed the race test (I assume it's because of the writings are at different memory location). But I'm wondering since the go-routines are accessing different keys of the map, why it will fail the race test?</p>