package main import ( "fmt" "sync" ) //演示slice协程不安全 var numbers = make([]int,0) func main() { var wg sync.WaitGroup for i:=0;i<1000 ;i++ { go func() { wg.Add(1) numbers=append(numbers,i) wg.Done() }() } wg.Wait() fmt.Println(len(numbers)) }
输出:
961
package main import ( "fmt" "sync" ) //演示slice协程不安全 var numbers = make([]int,0) func main() { var wg sync.WaitGroup for i:=0;i<1000 ;i++ { go func() { wg.Add(1) numbers=append(numbers,i) wg.Done() }() } wg.Wait() fmt.Println(len(numbers)) }
输出:
961