This commit is contained in:
wagslane
2023-05-01 15:25:27 -06:00
parent f8912668b8
commit 9be3074de6
868 changed files with 58698 additions and 2 deletions

View File

@@ -0,0 +1,7 @@
{
"question": "Can readers and writers use RWMutexes at the same time?",
"answers": [
"No",
"Yes"
]
}

View File

@@ -0,0 +1,51 @@
# Read/Write Mutex Review
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.
```go
package main
import (
"fmt"
"sync"
)
func main() {
m := map[int]int{}
mux := &sync.RWMutex{}
go writeLoop(m, mux)
go readLoop(m, mux)
go readLoop(m, mux)
go readLoop(m, mux)
go readLoop(m, mux)
// stop program from exiting, must be killed
block := make(chan struct{})
<-block
}
func writeLoop(m map[int]int, mux *sync.RWMutex) {
for {
for i := 0; i < 100; i++ {
mux.Lock()
m[i] = i
mux.Unlock()
}
}
}
func readLoop(m map[int]int, mux *sync.RWMutex) {
for {
mux.RLock()
for k, v := range m {
fmt.Println(k, "-", v)
}
mux.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.