Tutorial by Examples

Any function can be invoked as a goroutine by prefixing its invocation with the keyword go: func DoMultiply(x,y int) { // Simulate some hard work time.Sleep(time.Second * 1) fmt.Printf("Result: %d\n", x * y) } go DoMultiply(1,2) // first execution, non-blocking go DoMu...
single channel, single goroutine, one write, one read. package main import "fmt" import "time" func main() { // create new channel of type string ch := make(chan string) // start new anonymous goroutine go func() { time.Sleep(time.Second) ...
Go programs end when the main function ends, therefore it is common practice to wait for all goroutines to finish. A common solution for this is to use a sync.WaitGroup object. package main import ( "fmt" "sync" ) var wg sync.WaitGroup // 1 func routine(i int...
When in a loop, the loop variable (val) in the following example is a single variable that changes value as it goes over the loop. Therefore one must do the following to actually pass each val of values to the goroutine: for val := range values { go func(val interface{}) { fmt.Println...
package main import ( "log" "sync" "time" ) func main() { // The WaitGroup lets the main goroutine wait for all other goroutines // to terminate. However, this is no implicit in Go. The WaitGroup must // be explicitely incremented pr...
package main import ( "fmt" "time" ) // The pinger prints a ping and waits for a pong func pinger(pinger <-chan int, ponger chan<- int) { for { <-pinger fmt.Println("ping") time.Sleep(time.Second) ponge...

Page 1 of 1