简体   繁体   中英

Goroutine storage channel value has no deadlock

This code runs and ends with no deadlock error. Why?

func main() {
    ch := make(chan int)
    go func() {
        ch<-1
        ch<-2
    }()

    time.Sleep(time.Second)
}

The unbuffered channel needs two end points to work, so let's start with correct example:

package main

func main() {
    go fun2()
    <-ch
    <-ch
}
func fun2() {
    ch <- 1
    ch <- 2
}

var ch = make(chan int)

Here fun2() sends two values and main() receives two values.


Your sample code has only one end point so the channel is not correctly constructed, so it is deadlock , but the main goroutines exits normally so you don't see the error. Here, there is no second end point, so this is deadlock:

package main

func main() {
    var ch = make(chan int)
    ch <- 1
}

Output:

fatal error: all goroutines are asleep - deadlock!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM