Home
Go
chan Example
This page was last reviewed on Nov 27, 2023.
Dot Net Perls
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.
WaitGroup
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.
func
Info The func uses three nested for-loops to waste some time. It does nothing important.
for
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.
fmt
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 27, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.