Search code examples
goconcurrencygoroutine

How do I close the channel correctly?


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.


Solution

  • 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)
    }