简体   繁体   中英

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?

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{}
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM