标签:会同 for 多个 读写 sync 加锁 有一个 run code
适用于读写不确定,并且只有一个读或者写的场景
package main
import (
"sync"
"time"
)
var (
l *sync.Mutex
i int
)
func increment() {
l.Lock()
defer l.Unlock()
i++
}
func main() {
l = new(sync.Mutex)
for i := 0; i < 1000; i++ {
go increment()
}
println("i=", i)
time.Sleep(time.Second)
}
适用于读多写少的场景
package main
import (
"sync"
"time"
)
var (
l *sync.RWMutex
i int
)
func write() {
println("write start")
l.Lock()
i++
l.Unlock()
println("write end")
}
func read() {
println("read start")
l.RLock()
time.Sleep(time.Millisecond * 100)
println("read end, i =", i)
l.RUnlock()
}
func main() {
l = new(sync.RWMutex)
go read()
go read()
go write()
time.Sleep(time.Second)
}
以上代码中,会同时启动两个读和一个写,上述代码i的值可能会出现三种情况:
标签:会同 for 多个 读写 sync 加锁 有一个 run code
原文地址:https://www.cnblogs.com/wining/p/9648314.html