使变量更新对其他Go协程可见

huangapple go评论83阅读模式
英文:

Make variable update visible to other go-routines

问题

Golang 新手。在我的程序中,一个后台 go 协程会定期检查环境并更新一个变量。这个变量在 HTTP 处理程序方法中用于服务客户端请求。所以基本上它是一种单值缓存,有一个更新者和多个消费者。

在像 Java 这样的语言中,简单地将这个变量声明为 volatile 可以确保更新后的值对所有消费者都可见。但是由于在 Go 中没有 volatile 选项,这里推荐的解决方案是什么?

读写锁(RW lock)可以工作,但对于这种简单的场景来说似乎有点过度设计。

或者这个问题可以通过通道进行通信来解决?

英文:

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?

答案1

得分: 3

我同意@Volker的观点,原子函数应该谨慎使用,但对于这个简单的场景,使用atomic.Value相对简单:

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

...

// 在写入的goroutine中:
envVar.Store(os.Getenv("ENVVAR"))

...

// 在读取的goroutine中:
v := envVar.Load().(string)
英文:

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)

答案2

得分: 2

如果Java原子变量能够满足您在Java应用程序中的需求,那么可以考虑使用Go语言的原子内存原语或更高级别的sync.Mutex / sync.RWMutex。

根据问题中提供的信息不足,无法确定应用程序是否可以结构化地充分利用通道。

英文:

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.

There's not enough information in the question to know if the application can be structured to make good use of channels.

huangapple
  • 本文由 发表于 2016年2月15日 11:03:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/35400859.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定