优雅地关闭通道并且不在关闭的通道上发送
时间:2024-04-13
浏览:463
作者:佚名
一分耕耘,一分收获!既然打开了这篇文章《优雅地关闭通道并且不在关闭的通道上发送》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!
我是 golang 并发的新手,一直在努力理解下面提到的这段代码。
我目睹了一些我无法解释为什么会发生的事情:
当在主函数中使用 i 小于等于 100000
for i <= 100000 {时,有时会为 nresults 和 countwrites 打印不同的值(在最后两个语句中)fmt.printf("结果写入次数 %d\n", nresults) fmt.printf("作业写入次数 %d\n", jobwrites)当使用 i 超过 1000000 时,它会给出
panic: send on closed channel
如何确保发送到作业的值不在关闭的通道上,然后在结果中收到所有值后,我们可以关闭通道而不会出现死锁?
package main
import (
"fmt"
"sync"
)
func worker(wg *sync.WaitGroup, id int, jobs <-chan int, results chan<- int, countWrites *int64) {
defer wg.Done()
for j := range jobs {
*countWrites += 1
go func(j int) {
if j%2 == 0 {
results <- j * 2
} else {
results <- j
}
}(j)
}
}
func main() {
wg := &sync.WaitGroup{}
jobs := make(chan int)
results := make(chan int)
var i int = 1
var jobWrites int64 = 0
for i <= 10000000 {
go func(j int) {
if j%2 == 0 {
i += 99
j += 99
}
jobWrites += 1
jobs <- j
}(i)
i += 1
}
var nResults int64 = 0
for w := 1; w < 1000; w++ {
wg.Add(1)
go worker(wg, w, jobs, results, &nResults)
}
close(jobs)
wg.Wait()
var sum int32 = 0
var count int64 = 0
for r := range results {
count += 1
sum += int32(r)
if count == nResults {
close(results)
}
}
fmt.Println(sum)
fmt.Printf("number of result writes %d\n", nResults)
fmt.Printf("Number of job writes %d\n", jobWrites)
}正确答案
您的代码中存在不少问题。
在封闭通道上发送
使用 Go 通道的一个一般原则是
不要从接收方关闭通道,如果通道有多个并发发送方,也不要关闭通道
(https://go101.org/article/channel-closing.html)
您的解决方案很简单:没有多个并发发送者,然后您可以从发送者端关闭通道。
不要为添加到通道的每个作业启动数百万个单独的 goroutine,而是运行一个执行整个循环的 goroutine 以将所有作业添加到通道。并在循环后关闭通道。工作人员将尽快消耗通道。
通过修改多个 goroutine 中的共享变量来进行数据竞争
您无需采取特殊步骤即可修改两个共享变量:
nResults,您将其传递给工作器中的countWrites *int64。i在写入作业通道的循环中:您从多个 goroutine 向其中添加 99,从而无法预测您实际写入jobs通道的值的数量
要解决1,有很多选择,包括使用sync.Mutex。但是,由于您只是添加它,最简单的解决方案是使用 atomic.AddInt64(countWrites, 1) 而不是 *countWrites += 1
要解决问题 2,每次写入通道时不要使用一个 Goroutine,而是在整个循环中使用一个 Goroutine(见上文)
理论要掌握,实操不能落!以上关于《优雅地关闭通道并且不在关闭的通道上发送》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
