Home > Software engineering >  Do sending more than 8 element to a channel can result in deadlock?
Do sending more than 8 element to a channel can result in deadlock?

Time:12-14

package main

import (
    "fmt"
    "time"
)

func printCount(c chan int) {
    num := 0
    for num >= 0 {
        num = <-c
        fmt.Print(num, " ")

    }
}

func main() {

    a := []int{8, 6, 7, 5, 3, 0, 9, -1, 3, 4}
    // If i use a := []int{8, 6, 7, 5, 3, 0, 9, -1} then it works fine

    c := make(chan int)

    go printCount(c)

    for _, v := range a {

        c <- v

    }

    time.Sleep(time.Second * 1)
    fmt.Println("End of main")
}

I try to send element of the slice to the channel and print it using golang. Now upto 8 element the program works fine. As i am adding 9th element in slice then deadlock conditions occures dont know why. I used to solve that by using the waitgroup but still not working.

CodePudding user response:

Sending a value through an (unbuffered) channel is always blocking, until it is received somewhere else.

I think your intention here is to send all values and then only print them if they are 0 or greater? You could alter your printCount like this:

func printCount(c chan int) {
    for num := range c {
        if num >= 0 {
            fmt.Print(num, " ")
        }
    }
}

https://goplay.space/#m5eT9AYDH-Q

CodePudding user response:

Hi just change c := make(chan int) to c := make(chan int, 100) where 100 is highest capacity of your channel:

package main
import (
    "fmt"
    "time"
)
func printCount(c chan int) {
    num := 0
    for num >= 0 {
        num = <-c
        fmt.Print(num, " ")
    }
}
func main() {
    a := []int{8, 6, 7, 5, 3, 0, 9, -1, 3, 4}
    // If i use a := []int{8, 6, 7, 5, 3, 0, 9, -1} then it works fine
    c := make(chan int, 40)
    go printCount(c)
    for _, v := range a {
        c <- v
    }
    time.Sleep(time.Second * 1)
    fmt.Println("End of main")
}

result:

8 6 7 5 3 0 9 -1 End of main

  • Related