Home > database >  How to print element in a buffer channel that has dynamic length in Golang?
How to print element in a buffer channel that has dynamic length in Golang?

Time:06-24

I store my data in a buffer channel, but length of channel may be less than its capacity.

After process some goroutine, I need to get all element in a channel, but I got deadlock error.

This is my code

package main

import (
    "fmt"
    )

func main() {
    a := []int{1, 2, 3, 4, 5} // Initialization of the slice a and 0 < n < len(a) - 1.
    difs := make(chan int, 5)

    for i := 0; i < len(a); i   {
        go func(a int, out chan<- int) {
            out <- a
        }(a[i], difs)
    }
    
    for i := range difs {
        fmt.Println(i)
    }
    
}

This is error I got

5
2
1
3
4
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
    /tmp/sandbox3158357866/prog.go:17  0x154

Program exited.

I don't know what I should do to resolve this problem

Anyone has good solution or example they could post?

CodePudding user response:

like they say

package main

import (
    "fmt"
    "sync"
)

func main() {
    a := []int{1, 2, 3, 4, 5} // Initialization of the slice a and 0 < n < len(a) - 1.
    difs := make(chan int, 5)

    var (
        wg sync.WaitGroup
    )
    for i := 0; i < len(a); i   {
        wg.Add(1)
        go func(a int, out chan<- int) {
            defer wg.Done()
            out <- a
        }(a[i], difs)
    }

    go func() {
        wg.Wait()
        close(difs)
    }()

    for i := range difs {
        fmt.Println(i)
    }

}

CodePudding user response:

To control the closing channel without any waiting just for data in channel you could try this solution:

package main

import (
    "fmt"
    )

func main() {
    a := []int{1, 2, 3, 4, 5} // Initialization of the slice a and 0 < n < len(a) - 1.
    difs := make(chan int, 5)

    for i := 0; i < len(a); i   {
        go func(a int, out chan<- int) {
            out <- a
        }(a[i], difs)
    }
    j := 1
    lenSl := len(a)
    for i := range difs {
        if(j == lenSl) {
           close(difs)
        }
        j  
        fmt.Println(i)
    }
    
}

  •  Tags:  
  • go
  • Related