当前位置:网站首页>Golang controls the number of goroutines and obtains processing results
Golang controls the number of goroutines and obtains processing results
2022-07-27 07:10:00 【Tie Zhu】
One 、 Preface
Recently encountered batch refresh ES The need for data , To speed up processing , That must be the first choice goroutine 了 , But as we all know ,goroutine The return value and error handling of have always been elusive ,go Get out easy , How to monitor go The result of going out is a problem .
1、goroutine Error handling of
sync.ErrGroup stay sync.WaitGroup On the basis of function , Added error passing , And cancel the whole... In case of an unrecoverable error goroutine aggregate , Or wait timeout .
You can learn more about Baidu .errGroup
2、goroutine Processing results of
Currently in use goroutine It is generally used that channel 、 sync.WaitGroup 、context, To realize the process control and message transmission between various processes , The first choice is channel To get the processing results ,channel Reference resources :go adopt channel obtain goroutine Processing results of .
except channel, So can we use concurrent security sync.Map To store the results , Of all the goroutine After execution , Get the processing results in a unified way ? The answer is yes ,sync.Map It can be perfectly realized .
Two 、 control goroutine Quantity and obtain processing results
1、 Combat code
Here are the USES goroutine Batch refresh ES data , And get the code of the processing result :
// Define the return value to get , Number of successes , The number of failures , Failure id aggregate
succeededNums, failedNums:= 0, 0,
errData:=""
var syncMap sync.Map
wg := sync.WaitGroup{
}
// control goroutine Number , At the same time, only 10 individual goroutine
chan1 := make(chan struct{
}, 10)
for {
// Business logic
// ....
//goroutine Speed up ,chan1 Write full , The block . Waiting for the previous goroutine Release to continue the cycle
chan1 <- struct{
}{
}
wg.Add(1)
go func(ctx context.Context, targetIndexName string, esClient *elastic.Client) {
defer func() {
if err1 := recover(); err1 != nil {
// Produced panic abnormal
log.Errorf(ctx, "%s go panic! err:(+%v)", logPreFix, err1)
}
wg.Done() // Every goroutine Release after execution
return
}()
bulkRequest := esClient.Bulk()
//ES Use bulk Method batch refresh data
bulkResByAssetInfo := new(EsBulkDataRes)
bulkResByAssetInfo, err = BulkEsDataByAssetInfo(ctx, bulkRequest, targetIndexName)
if err != nil {
log.Errorf(ctx, "%s BulkEsDataByAssetInfo error (%+v) ,test:(+%v)", logPreFix, err, string_util.TransferToString(fileUnitList))
return
}
// Accumulate the execution results to sync.map, Ensure concurrent security
tempMap := make(map[string]interface{
})
tempMap["successNums"] = bulkResByAssetInfo.SucceededNums
tempMap["failedNums"] = bulkResByAssetInfo.FailedNums
tempMap["errData"] = bulkResByAssetInfo.ErrData
// Take the maximum of each cycle id, As syncMap Of key
syncMap.Store(test[nums-1].ID, tempMap)
// Release after execution channel
<-chan1
}(ctx, targetIndexName, esClient)
}
wg.Wait()
// Refresh end , Write notification , The Notice includes , Traverse sync.map, Get the return value
syncMap.Range(func(key, value interface{
}) bool {
val := value.(map[string]interface{
})
succeededNums += val["successNums"].(int)
failedNums += val["failedNums"].(int)
errData += val["errData"].(string)
return true
})
// Print the results
fmt.Println(" Number of successes :",succeededNums)
fmt.Println(" The number of failures :",failedNums)
fmt.Println(" Failure id:",errData)
2、syncMap Use
(1) Write the processing result to map
(2) write in map To sync.Map in , Be careful key Don't repeat
(3) Use Range To cycle sync.Map, Get the results , Sum up
3、 control goroutine The number of
This is mainly through setting channel Length to achieve .
(1) Set up channel length , The cycle starts with each generation goroutine Write once channel
(2) channel If it is full, it will block
(3)goroutine completion of enforcement , Release channel
(4) for Continue writing in the loop channel, Ensure simultaneous execution goroutine Only 10 individual
3、 ... and 、sync.Map The shortcomings of
1、 Need to be right value Do assertion processing , This is interface{} The nature of
2、 Everybody knows sync.Map Suitable for reading more and writing less , Bloggers here are running scripts , So use sync.Map It doesn't hurt , If you want to pursue performance , You can look at it currentMap The implementation of the , adopt hash Points barrels , Reduce the granularity of locks to improve performance .
current-Map
end
边栏推荐
- deepsort源码解读(七)
- 工控用Web组态软件比组态软件更高效
- Error in running code: libboost_ filesystem.so.1.58.0: cannot open shared object file: No such file or directory
- DNA(脱氧核糖核酸)供应|碳纳米管载核酸-DNA/RNA材料|DNA/RNA核酸修饰磁性纳米颗粒
- PNA修饰多肽ARMS-PNA|PNA-DNA|suc-AAPF-pNA|Suc-(Ala)3-pNA
- Basic statement of MySQL (1) - add, delete, modify and query
- What is OKR and what is the difference between OKR and KPI
- DataScience:数据生成之在原始数据上添加小量噪声(可自定义噪声)进而实现构造新数据(dataframe格式数据存储案例)
- deepsort源码解读(四)
- 二叉树--天然的查找语义(1)基础篇
猜你喜欢

PNA peptide nucleic acid modified peptide suc Tyr Leu Val PNA | suc ala Pro Phe PNA 11

Norms of vectors and matrices

pytorch笔记:TD3

Vscode connection remote server development

Reflection on pytorch back propagation

基于SSM图书借阅管理系统

Quartus:往别人的工程添加.v文件报错

齐岳:巯基修饰寡聚DNA|DNA修饰CdTe/CdS核壳量子点|DNA偶联砷化铟InAs量子点InAs-DNA QDs

大疆livox定制的格式CustomMsg格式转换pointcloud2

Dajiang livox customized format custommsg format conversion pointcloud2
随机推荐
Talk about multimodality of fire
Watermelon book learning notes - Chapter 4 decision tree
Netease Yunxin appeared at the giac global Internet architecture conference to decrypt the practice of the new generation of audio and video architecture in the meta universe scene
二叉树--天然的查找语义(1)基础篇
R2live code learning record (3): radar feature extraction
36 - 新的 Promise 方法:allSettled & any & race
nvidia-smi 各参数意义
DNA偶联PbSe量子点|近红外硒化铅PbSe量子点修饰脱氧核糖核酸DNA|PbSe-DNA QDs
How to make the minimum API bind the array in the query string
含有偶氮苯单体的肽核酸寡聚体(NH2-TNT4,N-PNAs)齐岳生物定制
Basic statement of MySQL (1) - add, delete, modify and query
Book borrowing management system based on SSM
CdS quantum dots modified DNA | CDs DNA QDs | near infrared CdS quantum dots coupled DNA specification information
工控用Web组态软件比组态软件更高效
The qualities that a technical manager should have (guess)
2021 interview question of php+go for Zhongda factory (1)
Why can cross entropy loss be used to characterize loss
VIM editor deletes all file contents
Watermelon book chapter 3 - linear model learning notes
Peptide nucleic acid oligomer containing azobenzene monomer (nh2-tnt4, n-pnas) Qiyue biological customization