Created
March 8, 2016 14:39
-
-
Save gwind/5b8ce9bf1fe6ce91ede4 to your computer and use it in GitHub Desktop.
演示两个 goroutine 修改同一块数据结构
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 演示两个 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