Created
June 1, 2014 09:07
-
-
Save y-matsuwitter/2a557c57f37c59ec9770 to your computer and use it in GitHub Desktop.
sync.RWMutexを使おう ref: http://qiita.com/y_matsuwitter/items/36565a3a53ac52732cae
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ go run rwmutex.go | |
read_start | |
read_start | |
write_start | |
read_start | |
read_complete fuga | |
read_complete fuga | |
write_complete | |
read_complete piyo |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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