一个 goroutine 在另一个 goroutine 修改结构体时读取它是安全的吗?

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

Is it safe for one goroutine to read from a struct while another goroutine is modifying it?

问题

更具体地说,在我的情况下,我有一个Web服务器和一个全局可访问的结构体,Web服务器使用该结构体生成页面。我还有另一个Goroutine,它会定期更新该结构体的新值。这会引起问题吗?我需要实现一种机制来确保在更新时不会读取它吗?

英文:

More specifically, in my case I have a webserver and a globally-accesible struct that the web server uses to generate a page. I have another Goroutine that's always updating that struct with new values periodically. Will this cause issues? Do I need to implement a mechanism to ensure it's not reading while it's being updated?

答案1

得分: 2

不,那绝对不安全的定义,并且如果你进行测试的话,会被race detector捕捉到。你绝对需要同步访问,例如使用sync.Mutexsync.RWMutex

如果不是必须始终使用最新的值,你也可以允许每个goroutine缓存一个结构体的副本,然后定期从“主”副本更新它们的副本。如果频繁访问结构体,这可以帮助避免由于锁争用而导致的一些性能问题。

英文:

No, that is the very definition of not safe, and would be caught by the race detector if you tested it. You will absolutely need to synchronize access, for example using sync.Mutex or sync.RWMutex.

If it is not critical to always have the latest values, you can also allow each goroutine to cache a copy of the struct, and then regularly update their copy from the "master" copy every so often. If there is frequent access to the struct, this can help avoid some performance issues due to lock contention.

huangapple
  • 本文由 发表于 2017年8月15日 23:56:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/45696665.html
匿名

发表评论

匿名网友

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

确定