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.
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
and invoke it. We use the go
-keyword to call it as a goroutine.func
uses three nested for
-loops to waste some time. It does nothing important.func
returns the value of the variable res on the channel. This can be any int
value.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.