Channel Ownership

  • Default value for channels: nil
    • var ch chan interface{}
  • reading/writing to a nil channel will block forever.
var ch chan interface{}
<-ch
ch<-struct{}{}
  • closing nil channel will panic

    var ch chan interface{}
    close(ch)
    
  • Ensure the channels are initialized first.

  • Owner of channel is a goroutine that instantiates, writes, and closes a channel.
  • Channel utilizers only have a read-only view into the channel.

Ownership of channels avoids

  • Deadlocking by writing to a nil channel.
  • Closing a nil channel (panic)
  • Writing to a close channel (panic)
  • Closing a channel more than once (panic)

Exercises

https://go.dev/play/p/RWO2Mm6GMDd

package main

import "fmt"

func main() {
    //TODO: create channel owner goroutine which return channel and
    // writes data into channel and
    // closes the channel when done.
    owner := func() <-chan int {
        ch := make(chan int)
        go func() {
            defer close(ch)
            for i := 0; i < 5; i++ {
                ch <- i
            }
        }()
        return ch
    }

    consumer := func(ch <-chan int) {
        // read values from channel
        for v := range ch {
            fmt.Printf("Received: %d\n", v)
        }
        fmt.Println("Done receiving!")
    }

    ch := owner()
    consumer(ch)
}
Received: 0
Received: 1
Received: 2
Received: 3
Received: 4
Done receiving!
© Kimi Tsai all right reserved.            Updated : 2023-07-12 09:04:54

results matching ""

    No results matching ""

    results matching ""

      No results matching ""