title: Is there a race condition in the golang implementation of mutex the m.state is read without atomic function
body: <p>In golang if two goroutines read and write a variable without mutex and atomic, that may bring data race condition.</p>
  
  <p>Use command <code>go run --race xxx.go</code> will detect the race point.</p>
  
  <p>While the implementation of Mutex in src/sync/mutex.go use the following code</p>
  
  <pre><code>       func (m *Mutex) Lock() {
     // Fast path: grab unlocked mutex.
     if atomic.CompareAndSwapInt32(&amp;m.state, 0, mutexLocked) {
         if race.Enabled {
             race.Acquire(unsafe.Pointer(m))
         }
         return
     }
  
     var waitStartTime int64
     starving := false
     awoke := false
     iter := 0
     old := m.state     // This line confuse me !!!
         ......
  </code></pre>
  
  <p>The code <code>old := m.state</code> confuse me, because m.state is read and write by different goroutine.</p>
  
  <p>The following function Test obvious has race condition problem. But if i put it in mutex.go, no race conditon will detect.</p>
  
  <pre><code># mutex.go
  func Test(){
      a := int32(1)
          go func(){
                  atomic.CompareAndSwapInt32(&amp;a, 1, 4)
          }()
          _ = a
  }
  </code></pre>
  
  <p>If put it in other package like src/os/exec.go, the conditon race problem will detect.</p>
  
  <pre><code>package main
  
  import(
      "sync"
      "os"
  )
  func main(){
      sync.Test()        // race condition will not detect
      os.Test()          // race condition will detect
  }
  </code></pre>