Created
July 21, 2014 02:31
-
-
Save jihchi/7d2bef75a4936d36c3ff to your computer and use it in GitHub Desktop.
Discuss: https://groups.google.com/forum/#!topic/golang-nuts/-0-pblAKXr0 Code source: http://play.golang.org/p/usN4s5iUga
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" | |
import "time" | |
import "sync" | |
//This datastructure never gets modified, only new ones created. | |
type Config struct { | |
a string | |
b string | |
} | |
var configMutex sync.Mutex | |
var globalconfig *Config = &Config{"foo", "bar"} | |
func fakeWatchForNewConfig() { | |
i := 0 | |
j := 0 | |
for { | |
time.Sleep(1 * time.Second) | |
i += 1 | |
j += 1 | |
configMutex.Lock() | |
globalconfig = &Config{fmt.Sprintf("foo%d", i), fmt.Sprintf("foo%d", j)} | |
configMutex.Unlock() | |
} | |
} | |
func SnapShotConfig() *Config { | |
configMutex.Lock() | |
ret := globalconfig | |
configMutex.Unlock() | |
return ret | |
} | |
func main() { | |
go fakeWatchForNewConfig() | |
for { | |
//conf is safe because it is immutable. | |
//the snapshot will never change, there are no data races. | |
conf := SnapShotConfig() | |
fmt.Println(conf.a, conf.b) | |
time.Sleep(1 * time.Second) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment