简体   繁体   中英

How does receiver side know data on a single channel was empty if there are multiple senders send data on that channel?

I have a simple example and don't know how to fix it to make it works as I expected.

It should print Result: 30 but the screen showed: fatal error: all goroutines are asleep - deadlock!

I think the problem at here is the statement for val := range data . It still wait to receive data when the data channel was empty. But I don't how to solve it, please help me out.

package main

import (
    "fmt"
)

func senderSide(data chan int) {
    num := 5
    for i := 1; i <= num; i++ {
        data <- i
    }
    // close(data) //panic: send on closed channel if uncomment it
}

func receiverSide(data chan int, resp chan int) {
    sum := 0
    for val := range data {
        sum += val
    }
    resp <- sum
}

func main() {
    data := make(chan int)
    resp := make(chan int)
    go senderSide(data)
    go senderSide(data)
    go receiverSide(data, resp)
    result := <-resp
    fmt.Printf("Result: %v\n", result) //result = 30
}

I don't really understand your question, but the deadlock is simple to explain. You never close the data chan, so the loop in recevierSide never closes, because it's constantly waiting for more data.

This in turn means it never sends the response, so the program deadlocks.

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