0
点赞
收藏
分享

微信扫一扫

GoLang之切片并发安全问题

何以至千里 2022-04-06 阅读 42
golang

文章目录

GoLang之切片并发问题

本文基于Windos系统上Go SDK v1.8进行讲解

1.介绍切片并发问题

关于切片的,Go语言中的切片原生支持并发吗?

2.实践检验真理

2.1不指定索引动态扩容并发向切片添加数据

func concurrentAppendSliceNotForceIndex() {
	sl := make([]int, 0)
	wg := sync.WaitGroup{}
	for index := 0; index < 100; index++ {
		k := index
		wg.Add(1)
		go func(num int) {
			sl = append(sl, num)
			wg.Done()
		}(k)
	}
	wg.Wait()
	fmt.Println(sl)
	fmt.Printf("final len(sl)=%d cap(sl)=%d\n", len(sl), cap(sl))
}
func main() {
	concurrentAppendSliceNotForceIndex()
	/*第一次运行代码后,输出:[2 0 1 5 6 7 8 9 10 4 17 11 12 13 14 15 16 21 18 19 20 23 22 24 25 26 39 27 28 29 30 31 35 55 54 56 57 58 59 60 61 62 64 63 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 86 91 92 93 94 96 95 97 98 99]
	final len(sl)=74 cap(sl)=128*/
	//第二次运行代码后,输出:省略切片元素输出... final len(sl)=81 cap(sl)=128
	//第二次运行代码后,输出:省略切片元素输出... final len(sl)=77 cap(sl)=128
}

2.2不指定索引动态扩容并发向切片添加数据

func concurrentAppendSliceForceIndex() {
	sl := make([]int, 100)
	wg := sync.WaitGroup{}
	for index := 0; index < 100; index++ {
		k := index
		wg.Add(1)
		go func(num int) {
			sl[num] = num
			wg.Done()
		}(k)
	}
	wg.Wait()
	fmt.Println(sl)
	fmt.Printf("final len(sl)=%d cap(sl)=%d\n", len(sl), cap(sl))
}
func main() {
	concurrentAppendSliceForceIndex()
	/*第一次运行代码后,输出:[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 7
	9 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99]
	final len(sl)=100 cap(sl)=100*/
	/*第一次运行代码后,输出:[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 7
	9 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99]
	final len(sl)=100 cap(sl)=100*/
	/*第一次运行代码后,输出:[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 7
	9 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99]
	final len(sl)=100 cap(sl)=100*/
}

3.回答切片并发安全问题

所以当别人问你slice支持并发时,你就可以这样回答它:

4.解决切片并发安全问题方式

采用sync.map解决切片并发安全

举报

相关推荐

0 条评论