如何正确关闭通道?

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

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{&quot;aaaaaa&quot;, &quot;fffff&quot;, &quot;ddddd&quot;, &quot;eeeee&quot;}

   for _, value := range lines {
      value := value
      c.Wait()
      go func() {
         chanStr &lt;- 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 (
    &quot;fmt&quot;

    &quot;github.com/zenthangplus/goccm&quot;
)

func main() {
    c := goccm.New(2)
    chanStr := make(chan string)
    lines := []string{&quot;aaaaaa&quot;, &quot;fffff&quot;, &quot;ddddd&quot;, &quot;eeeee&quot;}

    go func() {
        for value := range chanStr {
            fmt.Println(value)
        }
    }()

    for _, value := range lines {
        value := value
        c.Wait()
        go func() {
            chanStr &lt;- value
            c.Done()
        }()
    }

    c.WaitAllDone()
    close(chanStr)
}

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:

确定