如何正确关闭通道?

huangapple go评论139阅读模式
英文:

How do I close the channel correctly?

问题

据我理解,死锁出现的原因是通道没有关闭。如何关闭通道以解决死锁问题?

我使用这个库来限制 goroutine 的数量:https://github.com/zenthangplus/goccm

代码:

  1. func main() {
  2. c := goccm.New(5)
  3. chanStr := make(chan string)
  4. lines := []string{"aaaaaa", "fffff", "ddddd", "eeeee"}
  5. for _, value := range lines {
  6. value := value
  7. c.Wait()
  8. go func() {
  9. chanStr <- value
  10. c.Done()
  11. }()
  12. }
  13. for value := range chanStr {
  14. fmt.Println(value)
  15. }
  16. c.WaitAllDone()
  17. }

在此之前,我使用通道 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:

  1. func main() {
  2. c := goccm.New(5)
  3. chanStr := make(chan string)
  4. lines := []string{&quot;aaaaaa&quot;, &quot;fffff&quot;, &quot;ddddd&quot;, &quot;eeeee&quot;}
  5. for _, value := range lines {
  6. value := value
  7. c.Wait()
  8. go func() {
  9. chanStr &lt;- value
  10. c.Done()
  11. }()
  12. }
  13. for value := range chanStr {
  14. fmt.Println(value)
  15. }
  16. c.WaitAllDone()
  17. }

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中从通道中读取:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/zenthangplus/goccm"
  5. )
  6. func main() {
  7. c := goccm.New(2)
  8. chanStr := make(chan string)
  9. lines := []string{"aaaaaa", "fffff", "ddddd", "eeeee"}
  10. go func() {
  11. for value := range chanStr {
  12. fmt.Println(value)
  13. }
  14. }()
  15. for _, value := range lines {
  16. value := value
  17. c.Wait()
  18. go func() {
  19. chanStr <- value
  20. c.Done()
  21. }()
  22. }
  23. c.WaitAllDone()
  24. close(chanStr)
  25. }
英文:

Read from the channel in another goroutine:

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;github.com/zenthangplus/goccm&quot;
  5. )
  6. func main() {
  7. c := goccm.New(2)
  8. chanStr := make(chan string)
  9. lines := []string{&quot;aaaaaa&quot;, &quot;fffff&quot;, &quot;ddddd&quot;, &quot;eeeee&quot;}
  10. go func() {
  11. for value := range chanStr {
  12. fmt.Println(value)
  13. }
  14. }()
  15. for _, value := range lines {
  16. value := value
  17. c.Wait()
  18. go func() {
  19. chanStr &lt;- value
  20. c.Done()
  21. }()
  22. }
  23. c.WaitAllDone()
  24. close(chanStr)
  25. }

huangapple
  • 本文由 发表于 2023年3月20日 16:04:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75787773.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定