gf/.example/container/gmap/safe_map_delete.go

40 lines
610 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"fmt"
"sync"
"time"
)
// 验证 map 的delete方法是否并发安全
func main() {
// 创建一个初始化的map
m := make(map[int]int)
for i := 0; i < 10000; i++ {
m[i] = i
}
fmt.Println("map size:", len(m))
wg := sync.WaitGroup{}
ev := make(chan struct{}, 0)
// 创建10个并发的goroutine使用ev控制并发开始事件更容易模拟data race
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
<-ev
fmt.Println("start")
for i := 0; i < 10000; i++ {
delete(m, i)
}
wg.Done()
}()
}
time.Sleep(time.Second)
close(ev)
wg.Wait()
}