A goroutine is a function that can run concurrently. You can see it as a lightweight thread.
The idea stems from concurrency: working on more than one task simultaniously.
To invoke a Go routine, write
go before the function call.
If you have a function
f(string), call it as
go f(string) to invoke it as goroutine. The function will then run asynchronously.
Learn How To Code: Google’s Go (golang) Programming Language
The code below invokes a goroutine, calls the function and waits for keyboard input. The goroutine is executed concurrently.
go f("go routine")
Go doesn’t wait for goroutines to finished, it will return to the next line and run a goroutine concurrently. Without
fmt.Scanln() Go would finish the program.
The goroutine defined
f(msg string) is a simple function that outputs a line of text. It is called both as a regular function and as a goroutine.
Goroutines are light on memory, a program can easily have hundreds or thousands of goroutines.
This example starts a goroutine:
$ go run example.go function go routine
- What is a goroutine?
- How can you turn a function into a goroutine?
- What is concurrency?