Skip to content

Instantly share code, notes, and snippets.

@gwind
Created March 8, 2016 14:39
Show Gist options
  • Save gwind/5b8ce9bf1fe6ce91ede4 to your computer and use it in GitHub Desktop.
Save gwind/5b8ce9bf1fe6ce91ede4 to your computer and use it in GitHub Desktop.
演示两个 goroutine 修改同一块数据结构
// 演示两个 goroutine 修改同一块数据结构
// TODO: 加上锁
package main
import "fmt"
func updateData(a *[]int, quit chan int) {
for i := 20; i < 30; i++ {
*a = append(*a, i)
}
close(quit)
}
func main() {
quit := make(chan int)
var data []int
// go 1 update!
go updateData(&data, quit)
// go 2 update!
for i := 0; i < 10; i++ {
data = append(data, i)
}
// wait
<-quit
fmt.Println(data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment