简体   繁体   中英

deadlock in golang

I know by exchanging line 15 and line 17 gives no error, however, I don't understand why not exchange will gives deadlock

package main

import (
    "fmt"

)

func greet(c chan string) {
    fmt.Println("Hello " + <-c + "!")
}

func main() {
    c := make(chan string)
    //line15
    c <- "John"
    //line17
    go greet(c)

}

fatal error: all goroutines are asleep - deadlock!

The channel c is unbuffered. Communication on an unbuffered channel does not proceed until the sender and receiver are both ready.

The program deadlocks because no receiver is ready when the main goroutine executes the send operation.

You can do something like this

package main

import (
    "fmt"
    "sync"
)

func greet(c chan string, wg *sync.WaitGroup) {
    defer wg.Done()
    fmt.Println("Hello " + <-c + "!")
}

func main() {
    c := make(chan string, 10)
    //line15
    c <- "John"
    //line17
    var wg sync.WaitGroup
    wg.Add(1)
    go greet(c, &wg)
    c <- "Alex"
    wg.Add(1)
    go greet(c, &wg)
    wg.Wait()

}

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