Goroutines
You can define, create, and execute a new goroutine using the go
keyword followed by a function name or an anonymous function. The go
keyword makes the function call return immediately, while the function starts running in the background as a goroutine and the rest of the program continues its execution. You cannot control or make any assumptions about the order in which your goroutines are going to be executed because that depends on the scheduler of the OS, the Go scheduler, and the load of the OS.
Creating a goroutine
In this subsection, we learn how to create goroutines. The program that illustrates the technique is called create.go
. The implementation of the main()
function is as follows:
func main() {
go func(x int) {
fmt.Printf("%d ", x)
}(10)
This is how you run an anonymous function as a goroutine. The (10)
at the end is how you pass a parameter to an anonymous function. The previous anonymous function just prints...