Golang : Channels and buffered channels examples

Tags : golang channels

Continue from previous tutorial on goroutines. Goroutines run in the same memory address space and how does Golang allow communications between different goroutines?

Golang has channels. Imagine channels as the pipes that connect concurrent goroutines. You can send values into channels from one goroutine and receive those values at another goroutine.

Just think of channel similar to Unix/Linux pipe |

For example :

>ls -al | grep hello - ls command passing data via pipe | to grep command.

Some examples of making new channels in Golang :

chint := make(chan int)

chstr := make(chan string)

chitf := make(chan interface{})

channel uses the operator <- to send or receive data.

ch <- v // send v to channel ch.

v := <-ch // receive data from ch, and assign to v

Demo :

 package main

 import "fmt"

 func say(msg chan<- string) {
  msg <- "Hello, 世界!"

 func main() {
  message := make(chan string)

  go say(message)


Output :

Hello, 世界!

Be default, sending and receiving data in channels are blocked. It means that a goroutine expecting data will NOT continue until it receive the data.

So far, we have only see single element channels. Golang has another type of channel that allow more than one element to pass through and it is known as the buffered channel.

The different between buffered channel and normal channel is the n parameter :

ch := make(chan type, n)

To declare a buffered channel, you need to specify the number of elements.

For example :

ch := make(chan bool, 4) // to send/receive 4 boolean elements.

n == 0 ! non-buffer(block)

n > 0 ! buffered channel.(non-block until n elements in the channel)

This code example below demonstrate a buffered channel in action

 package main

 import "fmt"

 func main() {
  c := make(chan int, 2) // change n=2 to n=1 will cause deallock error , but not n=3
  c <- 1
  c <- 2

Output :



if change n to 1

fatal error: all goroutines are asleep - deadlock!

Hope this tutorial will help you to understand better on Golang channels.

SEE ALSO ON CHANNEL DIRECTION TYPE USAGE! at https://www.socketloop.com/references/golang-reflect-chandir-type-example

  See also : Golang : Concurrency and goroutine example

Tags : golang channels

By Adam Ng

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.