学习笔记,写到哪是哪。
读写锁是我们工作中常用的,说白了,可以同时读,但是不能同时写。
样例代码如下
package main
import (
"fmt"
"sync"
"time"
)
var (
rwCount int
myRWLock sync.RWMutex
wg2 sync.WaitGroup
)
func ReadCount() int {
myRWLock.RLock()
fmt.Println("ReadCount readlock ")
time.Sleep(time.Second)
defer myRWLock.RUnlock()
defer fmt.Println("ReadCount unreadlock ")
return rwCount
}
func ReadCount1() int {
myRWLock.RLock()
fmt.Println("ReadCount1 readlock ")
time.Sleep(time.Second)
defer myRWLock.RUnlock()
defer fmt.Println("ReadCount1 unreadlock ")
return rwCount
}
func HandleCount() {
myRWLock.Lock()
fmt.Println("HandleCount writelock ")
time.Sleep(time.Second)
defer myRWLock.Unlock()
defer fmt.Println("HandleCount unwritelock ")
rwCount += 1
}
func main() {
wg2.Add(3)
go func() {
defer wg2.Done()
for i := 0; i < 11; i++ {
fmt.Println("count1 -> ", ReadCount())
}
}()
go func() {
defer wg2.Done()
for i := 0; i < 11; i++ {
fmt.Println("count2 -> ", ReadCount1())
}
}()
go func() {
defer wg2.Done()
for i := 0; i < 10; i++ {
HandleCount()
fmt.Println("count -> add 1")
}
}()
wg2.Wait()
}
执行结果片段
ReadCount1 readlock
ReadCount readlock
ReadCount1 unreadlock
count2 -> 0
ReadCount unreadlock
count1 -> 0
HandleCount writelock
HandleCount unwritelock
count -> add 1
ReadCount readlock
ReadCount1 readlock
ReadCount1 unreadlock
count2 -> 1
ReadCount unreadlock
count1 -> 1
注意
1、可以看到两个读数据协程都可以获取到读锁。
2、使用了 sync.WaitGroup进行协程等待。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)