Safe to read from shared data structure in goroutines without channels

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

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) &gt; 30 {
				events = nil
			}
			event := &quot;The time is now &quot; + time.Now().String()
			events = append(events, event)
			time.Sleep(time.Millisecond * 200)
		}
	}()

	for {
		for i:=0; i &lt; len(events); i++ {
			fmt.Println(events[i])
		}
		time.Sleep(time.Millisecond * 100)
		fmt.Println(&quot;--------------------------------------------------------&quot;)
	}
}

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.

huangapple
  • 本文由 发表于 2020年10月19日 00:24:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/64415623.html
匿名

发表评论

匿名网友

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

确定