golang的append并发不安全

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
}

执行一下,发现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

转载请注明:小Y » golang的append并发不安全

赞 (0) 评论 (0) 分享 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址