doushishi6513 2019-08-01 20:48
浏览 57
已采纳

如何在goroutine中附加结构

I have a goroutine with a switch which want to append an interface to a struct but when a run it I don't receive an error but it not append any response How do you write that in Go to make it concurrency-safe?

This is my code:

var wg sync.WaitGroup

for _, v := range inputParameters.Entities {
    go func(v domain.Entity) {
        wg.Add(1)
        defer wg.Done()

        var f func(
            v domain.Entity,
            result *domain.Resoponse,
        )(interface{}, Error) // Signature of all Get methods

        switch v.Name {
        case "process1":
            f = 1Processor{}.Get
        case "process2":
            f = 2Processor{}.Get
        case "process3":
            f = 3Processor{}.Get
        default:
            return
        }
        res, err := f(v, result)

        if err != nil {
            mapError.Error = append(mapError.Error, err)
        } else {
            result.Mu.Lock()
            defer result.Mu.Unlock()
            result.Entities = append(result.Entities, res)
        }
    }(v)
}

wg.Wait()
return result, mapError

For reference, here is the Response type:

type Resoponse struct {
    Mu      sync.Mutex
    Entities []interface{}
}
  • 写回答

1条回答 默认 最新

  • duan198727 2019-08-01 21:35
    关注

    Do wg.Add(1) just before the goroutine. There's no guarantee that any of the logic within the goroutines gets done before you reach wg.Wait() so don't put the wg.Add(1)s in the goroutines.

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

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c