英文:
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.Mutex
或sync.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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论