golang 并发写map修复

2023-10-27  本文已影响0人  yandaxin

fatal error: concurrent map writes:当其中有两个goroutine 尝试同时写入相同的key 值时,就会引发 concurrent map writes 错误,为了解决该问题,可以使用Go 中的并发安全的结构体 sync.Map,或者使用互斥锁sync.Mutex以及concurrentmap 来保护map 的并发访问

https://blog.csdn.net/EDI451553616/article/details/130400507

teamValidMap := new(sync.Map)
    // 获取有效的队伍
    var wg sync.WaitGroup
    for _, teamItem := range teamList {
        wg.Add(1)

        tid := teamItem.TeamId
        teamTmp := teamItem
        go func(tid int64) {
            isV := IsTeamValid(ctx, teamTmp)
            teamValidMap.Store(tid, isV)
            defer wg.Done()
        }(tid)
    }
    wg.Wait()

    // 如果有多个队伍 选最后发起的有效的那个
    var team *InvitationTeam
    for _, teamItem := range teamList {
        isV, _ := teamValidMap.Load(teamItem.TeamId)
        if !isV.(bool) {
            continue
        }

        if nil == team {
            team = teamItem
            continue
        }

        if teamItem.InitiateTime.Unix() > team.InitiateTime.Unix() {
            team = teamItem
        }
    }

上一篇下一篇

猜你喜欢

热点阅读