Concurrency

RWMutex

RWMutex allows all the readers to access the map at the same time, but a writer will lock out everyone else

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()
}
}

Range over a channel

Range will automatically break the loop when a channel is closed

for integer := range intChannel {
fmt.Printf("%v ", integer)
}

Buffered channel

Buffered channels are channels that are given a capacity when they're instatiated. If no reads are perfomred on the channel,a goroutine can still performs n write, where n is the capacity of the bufferd channel

If a goroutine making writes to a channel has knowledge of how many writes it will make. It can be useful to create a bufferd channel whose capacity is the number of writes to be made, and then make those writes as quickly as possible

Last updated on