Fragment Description:



Channels.
The flow of data between send/receive channels must be managed precisely, to avoid unpleasant deadlocks.
It’s surprisingly easy to start goroutines and use channels.
It isn’t quite as easy to orchestrate their cleanup.
Avoiding deadlocks is also challenging.
Most often this boils down to an ordering problem, where a goroutine receiving on a go-chan exits before the upstream goroutines sending on it.
Try to modify the ordering of code in the main()...


channelGoodOrdering

Go Playground

Last update, on 2015, Fri 9 Oct, 16:15:27

/* ... <== see fragment description ... */

package main

import (
    "fmt"
    "time"
)

func processChannel(in <-chan int, out chan<- string) {
    // reading the "in" channel
    for inValue := range in {
        result := fmt.Sprintf("Hello %d", inValue)
        // sending result on the "out" channel
        out <- result
    }
    close(out)
}
func main() {
    // the flow is = sendChan -> in -> out -> receiveChan
    // instantiating
    receiveChan := make(chan string)
    sendChan := make(chan int)
    // ready to receive from processChannel, must start here: unless deadlock.
    go func() {
        for value := range receiveChan {
            fmt.Println(value)
        }
    }()
    // ready to Filter what is received from sendChan, must start here.
    go processChannel(sendChan, receiveChan)
    // Now we can start sending on sendChan, in and out are ready...
    for i := 0; i < 5; i++ {
        sendChan <- i
    }
    close(sendChan)
    time.Sleep(0.02 * 1e7)
}

/* Expected Output:
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
*/



Comments