What are channels used for?

Pim verleg picture Pim verleg · Oct 3, 2016 · Viewed 12k times · Source

When looking through some Go code I found the following:

  ch := make(chan int)

I looked up in a online tutorial how Go Channels work:

https://tour.golang.org/concurrency/2

But I find this example unclear.

Can someone give me a easy explanation and an example of the use of channels?

Answer

shivendra pratap singh picture shivendra pratap singh · Oct 3, 2016

chan is a channel in Golang. In simple word you can think it as a box in which you put a item at one end and then pick it from other end.

Unbuffered Channels

enter image description here

Buffered Channel

enter image description here

This is the small code I have written for you to understand channels. Now change order of go routines and see the outputs. Each time output may differ.

    package main

    import (
        "fmt"
        "time"
    )

    func main() {
        messages := make(chan int)
        go func() {
            time.Sleep(time.Second * 3)
            messages <- 1
        }()
        go func() {
            time.Sleep(time.Second * 2)
            messages <- 2
        }() 
        go func() {
            time.Sleep(time.Second * 1)
            messages <- 3
        }()
        go func() {
            for i := range messages {
                fmt.Println(i)
            }
        }()
        go func() {
            time.Sleep(time.Second * 1)
            messages <- 4
        }()
        go func() {
            time.Sleep(time.Second * 1)
            messages <- 5
        }()
        time.Sleep(time.Second * 5)
    }

For best understanding visit this blog where go routines and channels are described in GUI.

Visit http://divan.github.io/posts/go_concurrency_visualize/