我是 Golang 的新手,開始使用 goroutines。我很好奇在不使用通道或互斥鎖的情況下從另一個 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("--------------------------------------------------------") }}
- 1 回答
- 0 關注
- 90 瀏覽
添加回答
舉報
0/150
提交
取消