I'm new to golang
(whith Java
concurrency background). Consider this peace of code :
package main
import "fmt"
func sendenum(num int, c chan int) {
c <- num
}
func main() {
c := make(chan int)
go sendenum(0, c)
x, y := <-c, <-c
fmt.Println(x, y)
}
When I run this code , I get this error
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
/home/tarrsalah/src/go/src/github.com/tarrsalah/stackoverflow/chan_dead_lock.go:12 +0x90
exit status 2
I know, adding another go sendenum(0, c)
statement fix the issue, ... but
When and Where the deadlock happened ?
After it receives the 0, main
keeps on waiting on the receiving end of c
for another value to arrive (to put in the y
variable), but it never will, as the goroutine running main
is the only one left to live.
When you add another go sendenum(0, c)
, it actually gets a value on the second channel receive, puts it into the y
variable, prints x
and y
out and the program finishes succesfully.
It's not that "reusing" a channel is a problem. It's just a simple deadlock happening because the code prescribes two reads, but only one write to the same channel. The second read can never happen, hence the 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.