title: Read preferring RW mutex lock in Golang
body: <p>I need a <a href="https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock" rel="noreferrer">read preferring RW</a> mutex in golang. Is there a package in golang that will satisfy my needs. I tried sync.RWMutex, but it seems to be write preferring lock. Here goes my attempt to distinguish Go's RWMutex,</p>
  
  <pre><code>package main
  
  import (
      "fmt"
      "sync"
      "time"
  )
  
  func main() {
  
  y := &amp;resource{x: 10}
  
  go func() {
      defer fmt.Println("done first read")
      y.RLock()
      defer y.RUnlock()
      go func() {
          defer fmt.Println("done first write")
          fmt.Println("first write req")
          y.Lock()
          fmt.Println("after first write granted")
          defer y.Unlock()
      }()
      time.Sleep(time.Second)
      go func() {
          defer fmt.Println("done second read")
          fmt.Println("second read req")
          y.RLock()
          fmt.Println("after second read granted")
          defer y.RUnlock()
      }()
  
      time.Sleep(10 * time.Second)
  }()
  
  time.Sleep(time.Minute)
  
  }
  
  type resource struct {
      sync.RWMutex
      x int
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>first write req
  second read req
  done first read
  after first write granted
  done first write
  after second read granted
  done second read
  </code></pre>
  
  <p>Second reader is kept waiting till the writer releases the lock.</p>