Concurrency
Examples
Filter
package main
import (
"fmt"
"time"
)
func main() {
fmt.Printf("Current Unix Time: %v\n", time.Now().Unix())
time.Sleep(2 * time.Second)
fmt.Printf("Current Unix Time: %v\n", time.Now().Unix())
}
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() {
// Calling f synchronously.
f("direct")
// To invoke this function in a goroutine, use go f(s).
// This new goroutine will execute concurrently with the calling one.
go f("goroutine")
// You can also start a goroutine for an anonymous function call.
go func(msg string) {
fmt.Println(msg)
}("going")
// Our two function calls are running asynchronously in separate goroutines now.
// Wait for them to finish (for a more robust approach, use a WaitGroup).
time.Sleep(time.Second)
fmt.Println("done")
}
Last Run
:
direct : 0
direct : 1
direct : 2
going
goroutine : 0
goroutine : 1
goroutine : 2
done
// The concurrency model is very similar to Go.
// To run foo() concurrently, just call it with go foo().
// Right now, it launches the function in a new system thread.
// Soon coroutines and the scheduler will be implemented.