Pankaj Bagwan
Pankaj Bagwan
1 min read

Categories

Tags

In last part, where we discussed Golang Concurrency, we talked about goroutines and channels. As discussed there is much more to channels, liked channel direction, by default a channel is bi-directional, but it can be restricted to sending or receiving.

In sender, receiver example from Golang Concurrency - Part 1, sender can only be restricted to sending, by redifining it like

func sender(ch chan <- int) {
  for i := 0; ; i++ {
    ch <- i
  }
}

Now sender can only send signal to channel ch. Similarly receiver can be restricted just to receive, by redifining it like

func receiver(ch <- chan int) {
  for {
    message := <- ch
    fmt.Println("received: ", message)
    time.Sleep(time.Millisecond * 100)
  }
}
Buffering in channels

Generally channels are synchronous, but they can have buffer of specified size. Buffer size can be specified by passing a second argument while creating a channel

ch := make(chan int, 10)

Now this channel can buffer at most 10 messages, working as a pub/sub.

Select

Select work like a case switch for channels, basic construct looks like:

select {
case message_from_ch1 := <- ch1:
    fmt.Println(message_from_ch1)
case message_from_ch2 := <- ch2:
    fmt.Println(message_from_ch2)
}

Happy Channeling :)


About The Author

I am Pankaj Baagwan, a System Design Architect. A Computer Scientist by heart, process enthusiast, and open source author/contributor/writer. Advocates Karma. Love working with cutting edge, fascinating, open source technologies.

  • To consult Pankaj Bagwan on System Design, Cyber Security and Application Development, SEO and SMO, please reach out at me[at]bagwanpankaj[dot]com

  • For promotion/advertisement of your services and products on this blog, please reach out at me[at]bagwanpankaj[dot]com

Stay tuned <3. Signing off for RAAM