

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: Mutexes in Go
incomplete
2: Why Is It Called a 'mutex'?
incomplete
3: Mutex Review
incomplete
4: RW Mutex
incomplete
5: Read/Write Mutex Review
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Maps are safe for concurrent read access, just not concurrent read/write or write/write access. A read/write mutex allows all the readers to access the map at the same time, but a writer will still lock out all other readers and writers.
package main
import (
"fmt"
"sync"
)
func main() {
m := map[int]int{}
mu := &sync.RWMutex{}
go writeLoop(m, mu)
go readLoop(m, mu)
go readLoop(m, mu)
go readLoop(m, mu)
go readLoop(m, mu)
// stop program from exiting, must be killed
block := make(chan struct{})
<-block
}
func writeLoop(m map[int]int, mu *sync.RWMutex) {
for {
for i := 0; i < 100; i++ {
mu.Lock()
m[i] = i
mu.Unlock()
}
}
}
func readLoop(m map[int]int, mu *sync.RWMutex) {
for {
mu.RLock()
for k, v := range m {
fmt.Println(k, "-", v)
}
mu.RUnlock()
}
}
By using a sync.RWMutex, our program becomes more efficient. We can have as many readLoop() threads as we want, while still ensuring that the writers have exclusive access.