NOTE
2.9 sync.RWMutex
What sync.RWMutex is and an example using write locks and read locks around a shared map.
This is a historical learning note and may contain outdated or incomplete understanding.
1. What It Is
- Implements the
Lockerinterface and is a read-write lock LockandRLockare used to acquire the write lock and read lock respectivelyUnlockandRUnlockare used to release the write lock and read lock respectively
2. Usage
const Size = 5
func TestSync3(t *testing.T) {
data := make(map[int]int)
var lock sync.RWMutex
var wg sync.WaitGroup
wg.Add(3)
go func() {
defer wg.Done()
for i := 0; i < Size; i++ {
lock.Lock()
data[i] = i
lock.Unlock()
time.Sleep(time.Second)
}
}()
for i := 0; i < 2; i++ {
go func() {
defer wg.Done()
for {
lock.RLock()
fmt.Println(data)
if len(data) == Size {
lock.RUnlock()
break
} else {
lock.RUnlock()
}
}
time.Sleep(time.Millisecond * 500)
}()
}
wg.Wait()
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub