Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ribice
Created February 3, 2020 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ribice/856278ec817c09ca2470ab8adc386a2e to your computer and use it in GitHub Desktop.
Save ribice/856278ec817c09ca2470ab8adc386a2e to your computer and use it in GitHub Desktop.
Golang map used for concurrent read/write
package main
import (
"fmt"
"sync"
"time"
)
var countryCities = map[string][]string{}
var mutex = &sync.RWMutex{}
func main() {
countryCities = make(map[string][]string)
countryCities["England"] = []string{"London", "Leeds", "Liverpool", "Bristol", "Cardiff"}
go func() {
for country := range countryCities {
go func() {
printCity(country)
}()
}
}()
go func() {
for _, city := range []string{"Sheffield", "Glasgow", "Manchester", "Bradford", "Edinburgh"} {
mutex.Lock()
countryCities["England"] = append(countryCities["England"], city)
mutex.Unlock()
time.Sleep(time.Millisecond * 1000)
}
}()
time.Sleep(time.Second * 6)
fmt.Println(countryCities)
}
func printCity(country string) {
var index int
for {
mutex.Lock()
if len(countryCities[country])-1 < index {
time.Sleep(2 * time.Second)
delete(countryCities, country)
mutex.Unlock()
return
}
fmt.Println(countryCities[country][index])
index++
mutex.Unlock()
time.Sleep(time.Millisecond * 300)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment