SenthilOO7
SenthilOO7

Reputation: 55

issue with go routine and channel

I am learning go routines and channels,here is a basic program which i tried on the topic ,I am getting error that fatal error: all goroutines are asleep - deadlock! and I also want to know why length of my channel is zero.

package main

import (
    "fmt"
)

func main() {

    mychannel := make(chan int)
    go takeChn(mychannel)

    fmt.Println("length", len(mychannel))

    for res := range mychannel {
        fmt.Println("firstFunc", res, len(mychannel))

    }

}

func takeChn(c chan int) {

    for i := 0; i < 10; i++ {
        c <- (i + 1)

    }
}

Upvotes: 0

Views: 60

Answers (2)

Gopher
Gopher

Reputation: 751

Modifying the code as per Burak Serdar's input by closing the channel

package main

import (
    "fmt"
)

func main() {

    mychannel := make(chan int)
    go takeChn(mychannel)

    fmt.Println("length", len(mychannel))

    for res := range mychannel {
        fmt.Println("firstFunc", res, len(mychannel))

    }

}

func takeChn(c chan int) {

    for i := 0; i < 10; i++ {
        c <- (i + 1)

    }
    close(c)
}

Output:

length 0
firstFunc 1 0
firstFunc 2 0
firstFunc 3 0
firstFunc 4 0
firstFunc 5 0
firstFunc 6 0
firstFunc 7 0
firstFunc 8 0
firstFunc 9 0
firstFunc 10 0

Upvotes: 0

Burak Serdar
Burak Serdar

Reputation: 51652

The length of the channel is zero, because it is an unbuffered channel. It does not store any elements.

Your program deadlocks because the for-loop never terminates. The range over the channel will terminate when the channel is closed, but you never close the channel.

If you close the channel at the end of the goroutine, the program will run without a deadlock.

Upvotes: 3

Related Questions