简体   繁体   中英

golang channel deadlock problems, should I close the channel

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.

  1. range unclosed ch1 will causing block;
  2. even close ch1, you can still receive data from ch1;
  3. It can be said, close(ch1) will send a special message to ch1, which can be used to notify the ch1 receiver that no more data will be received. So even if there is data in the ch1, you can close() without causing the receiver to not receive the remaining data.
  4. The channel does not need to release resources through close. As long as there is no goroutine holding the channel, the related resources will be automatically released. uncomment defer close(ch1) will solve this problems. here

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