Skip to content

Instantly share code, notes, and snippets.

@drewwells
Last active January 8, 2016 19:39
Show Gist options
  • Save drewwells/ae0a2b97181e072b7fbe to your computer and use it in GitHub Desktop.
Save drewwells/ae0a2b97181e072b7fbe to your computer and use it in GitHub Desktop.
sync access to map of pointers
package syncmap
import (
"fmt"
"sync"
)
type S struct {
name string
}
var m = make(map[string]*S)
var mu sync.Mutex
func set(key string, s *S) {
mu.Lock()
fmt.Printf("set (%p) %s\n", s, s)
m[key] = s
mu.Unlock()
}
func get(key string) *S {
mu.Lock()
defer mu.Unlock()
return m[key]
}
package syncmap
import (
"fmt"
"testing"
)
func TestSync(t *testing.T) {
go func() {
set("key", &S{name: "a"})
s := get("key")
s.name = "c"
fmt.Println(get("key"))
}()
set("key", &S{name: "b"})
s := get("key")
s.name = "d"
set("key", s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment