簡體   English   中英

如何在goroutine中附加結構

[英]How to append a struct in a goroutine

我有一個帶有開關的goroutine,它希望將接口附加到結構上,但是在運行時我沒有收到錯誤,但沒有附加任何響應如何在Go中編寫該代碼以使其並發安全?

這是我的代碼:

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

供參考,以下是Response類型:

type Resoponse struct {
    Mu      sync.Mutex
    Entities []interface{}
}

在goroutine之前執行wg.Add(1) 無法保證在到達wg.Wait()之前,goroutine中的任何邏輯wg.Wait()完成,因此請勿將wg.Add(1)放入goroutine中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM