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.
Here In this example we create a func and invoke it. We use the go-keyword to call it as a goroutine.
Info The func uses three nested for-loops to waste some time. It does nothing important.
Return 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.
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)
}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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 16, 2025 (edit link).