Created
February 3, 2020 10:02
-
-
Save ribice/856278ec817c09ca2470ab8adc386a2e to your computer and use it in GitHub Desktop.
Golang map used for concurrent read/write
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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