Golang Chan: Channels, Make Examples

These Go examples use the chan keyword to create channels. They run concurrent funcs that signal completion.

Channel, goroutine. A goroutine is a method called in an asynchronous way.

A method can be called as a goroutine with the go-keyword. This creates many possibilities.

 

 

With channels, we can return values from our asynchronous goroutines. We specify channels with the chan-keyword. We make channels with make.

 

 

Channel example. Let us combine these concepts into a simple program that makes sense. This program creates a channel named "c." The channel returns an int.

 

Func: In this example we create a func and invoke it. We use the go-keyword to call it as a goroutine.

Computation: The func uses three nested for-loops to waste some time. It does nothing important.

Chan: The func returns the value of the variable res on the channel. This can be any int value.

Then: A PrintLn statements is executed—before the computation finishes. The channel result is waited for, and then printed.

Based on:

Golang 1.4

Golang program that uses chan, makes channel

package main

import "fmt"

func main() {
    // Make a channel that returns an int.
    c := make(chan int)

    // Call this func.
    go func() {
	// This does a long-running numerical computation.
	// ... It increments a number, then decrements it.
	res := 0
	for i := 0; i < 100; i++ {
	    for x := 0; x < 10000; x++ {
		for z := 0; z < 10000; z++ {
		    res++
		}
		for z := 0; z < 10000; z++ {
		    res--
		}
	    }
	}
	// Return the counter on the channel.
	c <- res
    }()

    fmt.Println("HERE")

    // Wait for result of func, store value in local.
    res := <-c
    fmt.Println("DONE")
    fmt.Println("RESULT =", res)
}

Output

HERE
DONE
RESULT = 0

With asynchronous programs, we can better wield the power of modern computers. We can compute results faster. But some complexity is introduced.

 

In its modern design, Go has a good solution to asynchronous problems. With chan and goroutines (that use the go keyword) we run code on several threads at once.