Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make variable update visible to other go-routines

Tags:

go

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?

like image 990
Felix Avatar asked Oct 23 '25 16:10

Felix


1 Answers

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)
like image 143
kostya Avatar answered Oct 26 '25 06:10

kostya