package main
import "fmt"
import "sync"
func main() {
fmt.Println("Hello world!")
for i:=0; i < 100; i++ {
TestAppend()
}
}
func TestAppend() (result []int) {
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
v := i
wg.Add(1)
go func() {
// other logic
result = append(result, v)
wg.Done()
}()
}
wg.Wait()
fmt.Printf("%v\n", len(result))
return result
}
import "fmt"
import "sync"
func main() {
fmt.Println("Hello world!")
for i:=0; i < 100; i++ {
TestAppend()
}
}
func TestAppend() (result []int) {
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
v := i
wg.Add(1)
go func() {
// other logic
result = append(result, v)
wg.Done()
}()
}
wg.Wait()
fmt.Printf("%v\n", len(result))
return result
}
执行一下,发现len(result)并不是像想象中的一直等于0
Hello world!
100
100
82
99
98
100
100
92
100
100
94
100
90
100
100
99
100
100
100
98
100
85
99
100
58
100
99
100
100
100
100
100
72
99
100
100
99
99
97
100
93
100
100
78
99
100
100
82
99
98
100
100
92
100
100
94
100
90
100
100
99
100
100
100
98
100
85
99
100
58
100
99
100
100
100
100
100
72
99
100
100
99
99
97
100
93
100
100
78
99
转载请注明:小Y » golang的append并发不安全