避免重复输出的 Go 并发工作池
今天golang学习网给大家带来了《避免重复输出的 Go 并发工作池》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~
我正在编写一个程序,该程序同时从文本文件中逐字读取,以使用通道和工作池模式计算出现次数
该程序按以下流程工作:
- 读取文本文件(
readtext函数) readtext函数将每个单词发送到word通道- 每个 goroutine 都会执行
countword函数来计算地图中的单词数量 - 每个goroutine返回一个map,worker函数将struct的result值传递给
resultc通道 - 测试函数根据来自
resultc通道的结果值创建地图 - 打印第 5 步创建的地图
程序可以运行,但是当我尝试输入 fmt.println(0) 来查看如下所示的过程时
func computetotal() {
i := 0
for e := range resultc {
total[e.word] += e.count
i += 1
fmt.println(i)
}
}
程序终止而不显示/计算所有单词
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 all goroutines finished 16 17 18 map[but:1 cat's:1 crouched:1 fur:1 he:2 imperturbable:1 it:1 pointed:1 sat:1 snow:1 stiffly:1 the:1 was:2 with:1] total words: 27 38 ... 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 time taken for reading the book 5.8145ms
如果我在此处取消计算 total 函数语句中的 fmt.println() 注释,程序会正确显示结果,输出如下所示
all goroutines finished map[a:83 about:4 above:2 absolute:1 accepted:1 across:1 affection:1 after:1 again:5 wonder:2 wood:5 wooded:1 woody:1 work:1 worked:2 world:4 would:11 wrapped:1 wrong:1 yellow:2 yielded:1 yielding:1 counts continues ......] total words: 856 time taken for reading the book 5.9924ms
这是我的 readtext 实现
//ensure close words at the right timing
func readtext() {
file, err := os.open(filename)
if err != nil {
log.fatal(err)
}
defer file.close()
scanner := bufio.newscanner(file)
scanner.split(bufio.scanwords)
for scanner.scan() {
word := strings.tolower(scanner.text())
words <- strings.trim(word, ".,:;")
}
//time.sleep(1 * time.second)
close(words)
}
这是我使用工作池实现的字数统计
//call countword func,
func workerpool() {
var wg sync.waitgroup
for i := 1; i <= numofworker; i++ {
wg.add(1)
go worker(&wg)
}
wg.wait()
fmt.println("all goroutines finished")
close(resultc)
}
func worker(wg *sync.waitgroup) {
var tempmap = make(map[string]int)
for w := range words {
resultc <- countword(w, tempmap) //retuns result value
}
wg.done()
}
//creates a map each word
func countword(word string, tempmap map[string]int) result {
_, ok := tempmap[word]
if ok {
tempmap[word]++
return result{word, tempmap[word] + 1}
}
return result{word, 1}
}
最后,这是主函数
const FILENAME = "cat.txt"
const BUFFERSIZE = 3000
const NUMOFWORKER = 5
var words = make(chan string, BUFFERSIZE) //job
var resultC = make(chan Result, BUFFERSIZE)
var total = map[string]int{}
type Result struct {
word string
count int
}
func main() {
startTime := time.Now()
go readText()
go computeTotal()
workerPool() //blocking
fmt.Println(total)
endTime := time.Now()
timeTaken := endTime.Sub(startTime)
fmt.Println("total words: ", len(total))
fmt.Println("Time taken for reading the book", timeTaken)
}
我一直在寻找为什么该程序没有显示一致的结果,但我还无法弄清楚。我如何更改程序才能产生相同的结果?
正确答案
您必须按以下方式重写 computetotal 函数:
func computetotal(done chan struct{}) {
defer close(done)
i := 0
for e := range resultc {
total[e.word] += e.count
i += 1
fmt.println(i)
}
}
func main() {
computetotaldone := make(chan struct{})
go computetotal(computetotaldone)
...
workerpool() //blocking
<-computetotaldone
fmt.println(total)
}
添加 fmt.println 导致无效结果的原因是您的实现存在竞争条件。由于主函数 fmt.println(total) 和 computetotal 函数中的打印总计结果并行运行,因此不能保证 computetotal 在调用 fmt.println(total) 之前处理所有消息。如果没有 fmt.println,computetotal 函数在您的计算机上足够快以产生正确的结果。
建议的解决方案确保 computetotal 在调用 fmt.println(total) 之前完成。
countword 函数始终返回 count == 1 的结果。
这是增加计数的函数版本:
func countword(word string, tempmap map[string]int) result {
count := tempmap[word] + 1
tempmap[word] = count
return result{word, count}
}
但是保持这个想法! comcomputitatal假设cbcountzqbentzqbendcbendczqb的结果始终发送result中的工人始终发送result {word,1} ult {word,1} 直接来自 readtext。代码如下:
func computetotal() {
i := 0
for e := range resultc {
total[e.word] += e.count
i += 1
fmt.println(i)
}
}
func readtext() {
file, err := os.open(filename)
if err != nil {
log.fatal(err)
}
defer file.close()
scanner := bufio.newscanner(file)
scanner.split(bufio.scanwords)
for scanner.scan() {
word := strings.tolower(scanner.text())
resultc <- result{strings.trim(word, ".,:;"), 1}
}
close(resultc)
}
main() {
...
go readtext()
computetotal()
fmt.println(total)
...
}
通道操作的开销可能会抵消在单独的 goroutine 中运行 computetotal 和 readtext 的任何好处。下面是组合成单个 goroutine 的代码:
func main() {
file, err := os.open(filename)
if err != nil {
log.fatal(err)
}
defer file.close()
scanner := bufio.newscanner(file)
scanner.split(bufio.scanwords)
var total = map[string]int{}
for scanner.scan() {
word := strings.tolower(strings.trim(scanner.text(), ".,:;"))
total[word]++
}
fmt.println(total)
}
问题中的 countword 函数让我认为您的目标是计算每个工作人员中的单词数并将结果合并为总数。这是代码:
func computeTotal() {
for i := 1; i <= NUMOFWORKER; i++ {
m := <-resultC
for word, count := range m {
total[word] += count
}
}
}
func workerPool() {
for i := 1; i <= NUMOFWORKER; i++ {
go worker()
}
}
func worker() {
var tempMap = make(map[string]int)
for w := range words {
tempMap[w]++
}
resultC <- tempMap
}
...
var resultC = make(chan map[string]int)
...
func main() {
...
go readText()
workerPool()
computeTotal()
...
}
今天关于《避免重复输出的 Go 并发工作池》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
在 Go 语言中定义全局常量映射
- 上一篇
- 在 Go 语言中定义全局常量映射
- 下一篇
- 使用Sarama库为Kafka消费者自定义消息反序列化器
-
- Golang · Go问答 | 18分钟前 | 故障排查 · Go问答 · Go archive/zip RegisterCompressor FileHeader.Method
- Go archive/zip RegisterCompressor 为什么没有被调用
- 467浏览 收藏
-
- Golang · Go问答 | 45分钟前 |
- Go archive/tar 流式写入为什么会阻塞在 Close
- 458浏览 收藏
-
- Golang · Go问答 | 1小时前 | 标准库 · Go问答 · Go archive/tar 路径穿越 ErrInsecurePath
- Go archive/tar 解包时为什么会出现 ErrInsecurePath
- 142浏览 收藏
-
- Golang · Go问答 | 1小时前 |
- Go archive/tar 解包稀疏文件为什么占用空间变大
- 133浏览 收藏
-
- Golang · Go问答 | 1小时前 | 文件处理 · 标准库 · Go问答 · Go archive/tar PAXRecords tar归档
- Go archive/tar 读取 PAXRecords 后字段为什么会丢失
- 188浏览 收藏
-
- Golang · Go问答 | 2小时前 |
- Go tls.Config复用后修改字段造成并发数据竞争的处理
- 214浏览 收藏
-
- Golang · Go问答 | 3小时前 |
- Go net/http服务端读取请求体超时的超时器组织方式
- 261浏览 收藏
-
- Golang · Go问答 | 3小时前 | 错误处理 · go · 文件系统 · errors.Is io/fs fs.ErrNotExist fs.ErrPermission
- Go io/fs文件不存在与权限错误的分类处理
- 259浏览 收藏
-
- Golang · Go问答 | 1天前 |
- Go time.NewTimer替代高频time.After的资源控制方法
- 481浏览 收藏
-
- Golang · Go问答 | 1天前 | go · archive/zip FileHeader.Name Go zip ZIP目录条目 Go压缩包遍历
- Go zip压缩包目录条目为空时的遍历兼容方案
- 181浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 227次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 274次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 235次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 219次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 12次使用
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- Go sql.Tx提交成功前读取结果导致事务边界混乱的修复方法
- 2026-09-20 501浏览
-
- Go select 用 time.After 做超时有什么资源代价
- 2026-09-10 501浏览
-
- Go 取 range 变量地址为什么得到重复指针
- 2026-09-07 501浏览

