Golang newbie. In my program, a back group go-routine check environment and update a variable periodically. This variable is used in http handler method servers client request. So basically it is kind of single value cache has one updater and many consumers.
In language like Java, simply make this variable volatile could make sure updated value are visible to all those consumers. But since volatile is not an option in Go, what is the recommended solution here?
RW lock could work, but it seems overkill for this simple scenario.
Or this problem could be converted to communication via channel somehow?
I agree with @Volker that atomic functions should be used with care however for this simple scenario using atomic.Value is fairly straightforward:
var envVar atomic.Value
envVar.Store("")
...
// in write goroutine:
envVar.Store(os.Getenv("ENVVAR"))
...
// in read goroutine:
v := envVar.Load().(string)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With