Skip to content

Instantly share code, notes, and snippets.

@y-matsuwitter
Created June 1, 2014 09:07
Show Gist options
  • Save y-matsuwitter/2a557c57f37c59ec9770 to your computer and use it in GitHub Desktop.
Save y-matsuwitter/2a557c57f37c59ec9770 to your computer and use it in GitHub Desktop.
$ go run rwmutex.go
read_start
read_start
write_start
read_start
read_complete fuga
read_complete fuga
write_complete
read_complete piyo
package main
import (
"sync"
"time"
)
var mu sync.RWMutex
var data map[string]string
func main() {
data = map[string]string{"hoge": "fuga"}
mu = sync.RWMutex{}
go read()
go read()
go write()
go read()
time.Sleep(5 * time.Second)
}
func read() {
println("read_start")
mu.RLock()
defer mu.RUnlock()
time.Sleep(1*time.Second)
println("read_complete", data["hoge"])
}
func write() {
println("write_start")
mu.Lock()
defer mu.Unlock()
time.Sleep(2 * time.Second)
data["hoge"] = "piyo"
println("write_complete")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment