Last active
January 8, 2016 19:39
-
-
Save drewwells/ae0a2b97181e072b7fbe to your computer and use it in GitHub Desktop.
sync access to map of pointers
This file contains 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 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] | |
} |
This file contains 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 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