go by example part 3

This commit is contained in:
2022-01-05 22:56:08 +01:00
parent c1b7c64da2
commit c5983176c5
10 changed files with 337 additions and 0 deletions

View File

@@ -0,0 +1,32 @@
// A goroutine is a lightweight thread of execution
package main
import (
"fmt"
"time"
)
func f(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
}
}
func main() {
// normal function call f(s), running synchronously
f("direct")
// invoke functions in a goroutine, use go f(s)
// this new goroutine will execute concurrently with the calling one
go f("goroutine")
// start a goroutine for an anonymous function call
go func(msg string) {
fmt.Println(msg)
}("going")
// the two function calls are running asynchronously in separate goroutines now
// Wait for them to finish (alternate use WaitGroup)
time.Sleep(time.Second)
fmt.Println("done")
}