douyin2883 2014-09-09 13:02 采纳率: 0%
浏览 29
已采纳

更改地图数据时如何防止死锁

I try to write a function that validate data. Look at the following code:

func Create(name, email, password, local string, termOf bool) map[string]string {

    wait := new(sync.WaitGroup)
    mutex := new(sync.Mutex)
    errMsg := make(map[string]string)

    if !termOf {
        mutex.Lock()
        errMsg["termOf"] = translate(local, "text06")
        mutex.Unlock()
    }

    wait.Add(1)
    go func() {
        err := ValidateName(name, local)
        mutex.Lock()
        errMsg["name"] = err.Error()
        mutex.Unlock()
        wait.Done()
    }()

    wait.Add(1)
    go func() {
        err := ValidateEmail(email, local)
        mutex.Lock()
        errMsg["email"] = err.Error()
        mutex.Unlock()
        wait.Done()
    }()

    wait.Add(1)
    go func() {
        err := ValidatePassword(password, local)
        mutex.Lock()
        errMsg["password"] = err.Error()
        mutex.Unlock()
        wait.Done()
    }()

    wait.Wait()

    // If errors appear
    if len(errMsg) > 0 {
        return errMsg
    }

    return nil
}

As you can see here, I use three goroutines and in the goroutine I lock it to change errMsg variable map type. When I run the function, I've got compiler error

runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x14 pc=0x44206a]

But when I remove in the goroutine all errMsg inserts, then the function works. I do not know the reason what I do wrong.

  • 写回答

1条回答 默认 最新

  • dongmi1663 2014-09-09 13:09
    关注

    It is possible that err is nil when returning from ValidateName(), ValidateEmail() or ValidatePassword() calls.

    You should check err != nil before adding it to the map.

    if err != nil {
        mutex.Lock()
        errMsg["xxx"] = err.Error()
        mutex.Unlock()
    }
    

    In other words, this isn't the map errMsg which is the issue, but the value you want to put in it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大