Worker Pool并发模式中何时关闭结果通道?
目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《Worker Pool并发模式中何时关闭结果通道?》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~
我试图了解 golang 中的并发性是如何工作的,因为我正在尝试批量处理一个大型 json 文件,但我不确定何时应该关闭我的通道。下面是代码,
package main
import (
"fmt"
"os"
"time"
)
type order struct {
recipe string `json:"recipe"`
postcode string `json:"postcode"`
delivery timewithformat `json:"delivery"`
}
type timewithformat struct {
weekday string
starttime time.time
endtime time.time
valid bool
}
func main() {
input, err := os.open("test.json")
if err != nil {
fmt.println(err)
}
concurrency := 20
ingest := make(chan []order)
ret := make(chan map[string]int)
for x := 0; x < concurrency; x++ {
go processrecipesworker(ingest, ret)
}
go parseinmemory(input, ingest)
finalmap := make(map[string]int)
for v := range ret {
// combine all incoming results
for recipe, occurrence := range v {
if v, ok := finalmap[recipe]; ok {
finalmap[recipe] = occurrence + v
} else {
finalmap[recipe] = occurrence
}
}
}
//further processing on finalmap
}
func parseinmemory(input *os.file, ingest chan []order) {
data, _ := ioutil.readall(input)
var orders []order
if err := json.unmarshal(data, &orders); err != nil {
log.fatal(err.error())
}
batch := 100000
for i := 0; i < len(orders); i += batch {
j := i + batch
if j > len(orders) {
j = len(orders)
}
ingest <- orders[i:j]
}
close(ingest)
}
func processrecipesworker(in <-chan []helpers.order, r chan map[string]int) {
result := make(map[string]int)
for _, order := range <-in {
if v, ok := result[order.recipe]; ok {
result[order.recipe] = v + 1
} else {
result[order.recipe] = 1
}
}
r <- result
}
我是 golang 和并发的新手,如果我的代码需要更改,请告诉我。
如有困惑,请随时发表评论。
编辑 torek 代码的建议如下所示,
package main
import (
"fmt"
"os"
"time"
)
func main() {
input, err := os.Open("test.json")
if err != nil {
fmt.Println(err)
}
var wg sync.WaitGroup
concurrency := 20
inGest := make(chan []helpers.Order)
ret := make(chan map[string]int)
wg.Add(concurrency)
for x := 0; x < concurrency; x++ {
go processRecipesWorker(inGest, ret)
}
go ParseInMemory(input, inGest)
go (func(wg *sync.WaitGroup) {
wg.Wait()
close(ret)
})(&wg)
finalMap := make(map[string]int)
for v := range ret {
// Combine all incoming results
for recipe, occurrence := range v {
if v, ok := finalMap[recipe]; ok {
finalMap[recipe] = occurrence + v
} else {
finalMap[recipe] = occurrence
}
}
}
//Further processing on finalMap
}
func ParseInMemory(input *os.File, ingest chan []Order) {
data, _ := ioutil.ReadAll(input)
var orders []Order
if err := json.Unmarshal(data, &orders); err != nil {
log.Fatal(err.Error())
}
batch := 100000
for i := 0; i < len(orders); i += batch {
j := i + batch
if j > len(orders) {
j = len(orders)
}
ingest <- orders[i:j]
}
close(ingest)
}
func processRecipesWorker(in <-chan []helpers.Order, r chan map[string]int) {
// This will get us unique recipes and there occurrences
// FR- 1 & 2 completed
result := make(map[string]int)
for _, order := range <-in {
if v, ok := result[order.Recipe]; ok {
result[order.Recipe] = v + 1
} else {
result[order.Recipe] = 1
}
}
r <- result
defer wg.Done()
}
现在代码不会引发死锁,但当我有 10m 记录时它只处理 2m 记录,我知道它正在发生,因为所有例程都调用 done() 所以它结束了。但现在的问题是我什么时候应该调用 wg.done() 因为代码应该如何知道最后一批正在处理,我们可以调用 .done() 。
解决方案
你现在已经很接近了:
for _, order := range <-in {
...
}
是错误的。这会接收一批并循环遍历它,但您希望循环遍历所有接收到的批次,然后循环遍历每个批次:
for batch := range in {
for _, order := range batch {
...
}
}在您的特定示例中,您知道要启动的 goroutine 数量,您可以在不使用 waitgroup 方法的情况下执行此操作。
Here 您可以找到代码修改的示例,为了简洁起见,我省略了您从文件中读取的部分。
它归结为两个主要修改。首先,您需要一个额外的通道(在我的示例中,它称为 quit)来跟踪每个 goroutine 何时完成工作。另外,还有已完成的 goroutine 的计数器(示例中为 donejobs)。
因此,您的 processrecipesworker 方法应如下所示:
func processrecipesworker(in <-chan []order, r chan map[string]int, quit chan<- int) {
result := make(map[string]int)
for orders := range in {
for _, order := range orders {
if v, ok := result[order.recipe]; ok {
result[order.recipe] = v + 1
} else {
result[order.recipe] = 1
}
}
}
r <- result
quit <- 1
}
其次,您可以使用 for-select 循环,并带有标签来遍历发送到 ret 和 quit 通道的数据。
loop:
for{
select {
case v := <- ret:
// Combine all incoming results
for recipe, occurrence := range v {
if v, ok := finalMap[recipe]; ok {
finalMap[recipe] = occurrence + v
} else {
finalMap[recipe] = occurrence
}
}
case <-quit:
doneJobs++
fmt.Println(doneJobs)
if doneJobs >= concurrency {
break loop
}
}
}
通过使用 break loop 语句,您可以中断 select 和 for 循环。
总而言之,@torek 使用 waitgroup 的解决方案是一个很好的解决方案,它提供了 go 中使用的通用模式的用法。您可以在 this 关于 go 管道的文章中看到这一点,特别是在扇出扇入部分。这个答案只是提供了另一种运行程序的方法,而不使用 waitgroup 方法。
今天关于《Worker Pool并发模式中何时关闭结果通道?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
PHP版本NTS的意义及相关知识介绍
- 上一篇
- PHP版本NTS的意义及相关知识介绍
- 下一篇
- PHP字符转ASCII码的原理解析
-
- Golang · Go问答 | 6小时前 | go · 排查 ·
- Go 编译缓存与构建标签冲突的排查方法
- 429浏览 收藏
-
- Golang · Go问答 | 6小时前 | go · Go 依赖缺失 go.mod go mod tidy module graph pruning
- Go module graph pruning 造成依赖缺失的修复
- 380浏览 收藏
-
- Golang · Go问答 | 16小时前 | go · Go GODEBUG 构建缓存 gocacheverify
- Go GODEBUG gocacheverify 校验缓存一致性
- 313浏览 收藏
-
- Golang · Go问答 | 16小时前 |
- Go build 缓存命中异常时的清理与定位
- 226浏览 收藏
-
- Golang · Go问答 | 1天前 |
- Go cgo.Handle 管理 Go 值跨语言传递
- 403浏览 收藏
-
- Golang · Go问答 | 1天前 | CGO · 内存管理 · Go问答 · Go CGO unsafe.Pointer cgo.Handle runtime.Pinner
- Go cgo 指针规则导致 panic 的边界定位
- 223浏览 收藏
-
- Golang · Go问答 | 1天前 | go ·
- Go GOMAXPROCS 变化对并发吞吐的影响
- 417浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 302次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 358次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 357次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 324次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 143次使用
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- Go tls.GetCertificate 为什么收不到空 ServerName 请求
- 2026-09-27 501浏览
-
- Go sql.Tx提交成功前读取结果导致事务边界混乱的修复方法
- 2026-09-20 501浏览
-
- Go select 用 time.After 做超时有什么资源代价
- 2026-09-10 501浏览

