Skip to content

Instantly share code, notes, and snippets.

@sprt
Last active October 15, 2023 21:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sprt/44c664832079372e21dd582d679788f9 to your computer and use it in GitHub Desktop.
Save sprt/44c664832079372e21dd582d679788f9 to your computer and use it in GitHub Desktop.
Concurrent map using channels
package main
import "fmt"
type safeMap struct {
data map[string]string
readch, writech chan chan string
}
func newSafeMap() *concurrentMap {
m := &safeMap{
data: make(map[string]string),
readch: make(chan chan string),
writech: make(chan chan string),
}
go func() {
for {
select {
case ch := <-m.readch:
key := <-ch
ch <- m.data[key]
case ch := <-m.writech:
key := <-ch
value := <-ch
m.data[key] = value
}
}
}()
return m
}
func (m *safeMap) get(key string) string {
ch := make(chan string)
m.readch <- ch
ch <- key
return <-ch
}
func (m *safeMap) set(key, value string) {
ch := make(chan string)
m.writech <- ch
ch <- key
ch <- value
}
func main() {
m := newSafeMap()
done := make(chan bool)
go func() {
m.set("foo", "a")
done <- true
}()
m.set("bar", "b")
<-done
fmt.Println(m.get("foo"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment