我有一個(gè)帶有開(kāi)關(guān)的 goroutine,它想要將一個(gè)接口附加到一個(gè)結(jié)構(gòu)體,但是當(dāng)運(yùn)行它時(shí),我沒(méi)有收到錯(cuò)誤,但它沒(méi)有附加任何響應(yīng),你如何在 Go 中編寫(xiě)它以使其并發(fā)安全?這是我的代碼:var wg sync.WaitGroupfor _, 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作為參考,這里是Response類(lèi)型:type Resoponse struct { Mu sync.Mutex Entities []interface{}}
1 回答

小唯快跑啊
TA貢獻(xiàn)1863條經(jīng)驗(yàn) 獲得超2個(gè)贊
wg.Add(1)
在 goroutine 之前執(zhí)行。無(wú)法保證 goroutine 中的任何邏輯在您到達(dá)之前就已完成,wg.Wait()
因此不要將wg.Add(1)
s 放入 goroutine 中。
- 1 回答
- 0 關(guān)注
- 132 瀏覽
添加回答
舉報(bào)
0/150
提交
取消