Go Append concurrency problem

Source: Internet
Author: User
This is a created article in which the information may have evolved or changed.

Golang Append concurrency problem

package mainimport ("fmt""sync")func main() {var wg sync.WaitGroups := make([]int, 0, 1000)for i := 0; i < 1000; i++ {v := iwg.Add(1)go func() {s = append(s, v)wg.Done()}()}wg.Wait()fmt.Printf("%v\n", len(s))}结果第一次:928第二次:945第三次:986……多运行几次你就会发现,slice长度并不是1000,而是不停的在变,为什么呢?因为append并不是并发安全的。我们举一个简单例子,比如,当A和B两个协程运行append的时候同时发现s[1]这个位置是空的,他们就都会把自己的值放在这个位置,这样他们两个的值就会覆盖,造成数据丢失。那该怎么写?最简单的方式就是用锁,贴一个例子。package mainimport ("fmt""sync")func main() {var (wg    sync.WaitGroupmutex sync.Mutex)s := make([]int, 0, 1000)for i := 0; i < 1000; i++ {v := iwg.Add(1)go func() {mutex.Lock()s = append(s, v)mutex.Unlock()wg.Done()}()}wg.Wait()fmt.Printf("%v\n", len(s))}运行一下这个例子就会发现,s的长度总是1000。
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.