我遇到了这段代码,想知道这是否需要一个 R/W Mutex。
method(){
var (
wg sync.WaitGroup
rwm sync.RWMutex
vcnRegionMap map[string][]core.Vcn
)
vcnRegionMap = make(map[string][]core.Vcn)
// This loops helps us in filtering unused regions
// for composition of region/vcnid ds
for _, regionName := range regions {
wg.Add(1)
go func(ctx context.Context, region string, vcnRegionMap map[string][]core.Vcn, wg *sync.WaitGroup, rwm *sync.RWMutex) {
// for locking maps
defer wg.Done()
// TODO: make this conditional if a region is specified
c.network.SetRegion(region)
vcnResponse, err := c.network.ListVcns(ctx, core.ListVcnsRequest{
CompartmentId: &c.cID,
})
if err != nil {
logger.Debug(err.Error())
}
if len(vcnResponse.Items) == 0 {
logger.Info("status 404: No Vcns found under the given OCID and region: %s", region)
return
}
logger.Info("status 200: Vcns found under the given OCID and region: %s", region)
for _, item := range vcnResponse.Items {
logger.Debug("Vcn object: %s", *item.DisplayName)
// maps are not concurrency safe
rwm.Lock()
defer rwm.Unlock()
vcnRegionMap[region] = append(vcnRegionMap[region], item)
}
}(ctx, regionName, vcnRegionMap, &wg, &rwm)
}
wg.Wait()
}
由于每个 goroutine 都有自己的 map 副本,Mutex 是否有帮助,我们可以避免它以减少延迟吗?