简体   繁体   English

使变量更新对其他例程可见

[英]Make variable update visible to other go-routines

Golang newbie. Golang新手。 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. 在http处理程序方法服务器客户端请求中使用此变量。 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. 在像Java这样的语言中,只需使此变量为volatile即可确保所有这些使用者都可以看到更新的值。 But since volatile is not an option in Go, what is the recommended solution here? 但是由于在Go中不是volatile的选择,这里推荐的解决方案是什么?

RW lock could work, but it seems overkill for this simple scenario. RW锁定可以工作,但在这种简单情况下似乎过于矫kill过正。

Or this problem could be converted to communication via channel somehow? 还是可以通过某种方式将此问题转换为通过渠道进行沟通?

If Java atomic variables would meet your needs in a Java app, then consider using Go's atomic memory primitives or the higher-level sync.Mutex / sync.RWMutex . 如果Java原子变量可以满足您在Java应用程序中的需求,请考虑使用Go的原子内存原语或更高级别的sync.Mutex / sync.RWMutex

There's not enough information in the question to know if the application can be structured to make good use of channels. 问题中没有足够的信息来知道应用程序是否可以结构化以充分利用渠道。

I agree with @Volker that atomic functions should be used with care however for this simple scenario using atomic.Value is fairly straightforward: 我同意@Volker的观点,应该谨慎使用原子函数,但是对于这种使用atomic.Value的简单方案而言,它相当简单:

var envVar atomic.Value
envVar.Store("")

...

// in write goroutine:
envVar.Store(os.Getenv("ENVVAR"))

...

// in read goroutine:
v := envVar.Load().(string)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM