package main
import (
"fmt"
"sync"
)
func main(){
ch1 := make(chan int,100)
ct := 0
var wg sync.WaitGroup
wg.Add(1)
go func(){
//defer close(ch1)
for i:= 0; i < 10;i ++{
ch1 <- i
}
}()
go func(){
defer wg.Done()
for x := range ch1{
fmt.Println(x)
}
}()
wg.Wait()
fmt.Println("numbers:",ct)
}
Why this code will return fatal error: all goroutines are asleep - deadlock!
I've found if I closed the channel there will be no deadlock, but I don't know why it's like that. Do I have to close the channel after I inputted all items into the channel?
for range
over a channel only terminates if / when the channel is closed. If you don't close the channel and you don't send more values on it, the for range
statement will block forever, and so will the main
goroutine at wg.Wait()
.
The "sender" party should close the channel once it sent all values, signalling the "receiver" party that no more values will come on the channel.
So yes, you should close the channel:
go func() {
defer close(ch1)
for i := 0; i < 10; i++ {
ch1 <- i
}
}()
The for loop that reads from the channel will continue reading unless you close the channel. That is the reason for the deadlock, because the goroutine that reads from the channel is the only active goroutine, and there is no other goroutines that can write to it. When you close, the for loop terminates.
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.