英文:
Safe to read from shared data structure in goroutines without channels
问题
我是你的中文翻译助手,以下是你提供的代码的翻译:
我刚开始学习使用Golang,并开始使用goroutine。我想知道在没有使用通道或互斥锁的情况下,从另一个goroutine正在写入的数据结构中读取是否安全。在下面的示例中,events
数组对main函数和goroutine都是可见的,但是main函数只读取它,而goroutine则修改它。这被认为是安全的吗?
var events = []string{}
func main() {
go func() {
for {
if len(events) > 30 {
events = nil
}
event := "The time is now " + time.Now().String()
events = append(events, event)
time.Sleep(time.Millisecond * 200)
}
}()
for {
for i := 0; i < len(events); i++ {
fmt.Println(events[i])
}
time.Sleep(time.Millisecond * 100)
fmt.Println("--------------------------------------------------------")
}
}
谢谢。
英文:
I am new to Golang and starting to use goroutines. I am curious if it is safe to read from a data structure that is being written to by another goroutines without using channel or mutex. In the example below, the events
array is visible to main and goroutine, but main only reads from it and the goroutine is modifying it. Is this considered safe?
var events = []string{}
func main() {
go func() {
for {
if len(events) > 30 {
events = nil
}
event := "The time is now " + time.Now().String()
events = append(events, event)
time.Sleep(time.Millisecond * 200)
}
}()
for {
for i:=0; i < len(events); i++ {
fmt.Println(events[i])
}
time.Sleep(time.Millisecond * 100)
fmt.Println("--------------------------------------------------------")
}
}
Thanks.
答案1
得分: 1
不,这绝对不安全。你应该在访问events
时使用同步原语,或者重新设计以使用通道。
你的代码可能在特定的架构/操作系统上正常工作,但在稍微更改或在另一个架构/操作系统上可能会意外中断。
尝试使用-race
运行你的代码进行验证。你可能会看到WARNING: DATA RACE
的提示。
另请参考这个答案。
英文:
No, this is absolutely not safe. You should use synchronization primitives around access to events
, or redesign to use channels.
Your code may work fine today, on a specific architecture/OS, but it may break unexpectedly with small changes and/or on another architecture/OS.
Try to run your code with -race
to verify. You'll probably see WARNING: DATA RACE
.
See also this answer.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论