[英]How to append a struct in a 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? 我有一个带有开关的goroutine,它希望将接口附加到结构上,但是在运行时我没有收到错误,但没有附加任何响应如何在Go中编写该代码以使其并发安全?
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: 供参考,以下是
Response
类型:
type Resoponse struct {
Mu sync.Mutex
Entities []interface{}
}
Do wg.Add(1)
just before the goroutine. 在goroutine之前执行
wg.Add(1)
。 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. 无法保证在到达
wg.Wait()
之前,goroutine中的任何逻辑wg.Wait()
完成,因此请勿将wg.Add(1)
放入goroutine中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.