英文:
How do I close the channel correctly?
问题
据我理解,死锁出现的原因是通道没有关闭。如何关闭通道以解决死锁问题?
我使用这个库来限制 goroutine 的数量:https://github.com/zenthangplus/goccm
代码:
func main() {
c := goccm.New(5)
chanStr := make(chan string)
lines := []string{"aaaaaa", "fffff", "ddddd", "eeeee"}
for _, value := range lines {
value := value
c.Wait()
go func() {
chanStr <- value
c.Done()
}()
}
for value := range chanStr {
fmt.Println(value)
}
c.WaitAllDone()
}
在此之前,我使用通道 done 来判断所有 goroutine 是否完成,并关闭通道,但在此之前我没有限制 goroutine 的数量。
英文:
As far as I understand the deadlock appears because the channel is not closed. How do I close the channel to get rid of the deadlock?
I use this library to limit the number of goroutines: https://github.com/zenthangplus/goccm
Code:
func main() {
c := goccm.New(5)
chanStr := make(chan string)
lines := []string{"aaaaaa", "fffff", "ddddd", "eeeee"}
for _, value := range lines {
value := value
c.Wait()
go func() {
chanStr <- value
c.Done()
}()
}
for value := range chanStr {
fmt.Println(value)
}
c.WaitAllDone()
}
Before that I did with the channel done to realize that all goroutines are complete and close the channel, but before that I did not limit the number of goroutines.
答案1
得分: 2
在另一个goroutine中从通道中读取:
package main
import (
"fmt"
"github.com/zenthangplus/goccm"
)
func main() {
c := goccm.New(2)
chanStr := make(chan string)
lines := []string{"aaaaaa", "fffff", "ddddd", "eeeee"}
go func() {
for value := range chanStr {
fmt.Println(value)
}
}()
for _, value := range lines {
value := value
c.Wait()
go func() {
chanStr <- value
c.Done()
}()
}
c.WaitAllDone()
close(chanStr)
}
英文:
Read from the channel in another goroutine:
package main
import (
"fmt"
"github.com/zenthangplus/goccm"
)
func main() {
c := goccm.New(2)
chanStr := make(chan string)
lines := []string{"aaaaaa", "fffff", "ddddd", "eeeee"}
go func() {
for value := range chanStr {
fmt.Println(value)
}
}()
for _, value := range lines {
value := value
c.Wait()
go func() {
chanStr <- value
c.Done()
}()
}
c.WaitAllDone()
close(chanStr)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论