What is a goroutine?
- Go course
- Intermediate
- Lesson 1/80
- 4 min
Learn that a goroutine is a lightweight thread.
What is a goroutine?
A goroutine is a lightweight thread managed by the Go runtime. You start one by putting the go keyword before a function call.
Goroutines are far cheaper than OS threads: they start with a few kilobytes and millions can run at once. The Go scheduler spreads them across CPU cores automatically.
Goroutines share the same address space; so you use channels or the sync package to communicate. Direct access to shared memory causes data races.
Goroutine advantages
The biggest advantage of goroutines is cost. An OS thread reserves 1–8 MB of stack; a goroutine starts at 2 KB and grows on demand.
Go's G-M-P model schedules goroutines efficiently: G goroutine, M machine (OS thread), P processor (context). Idle P's steal work.
So hundreds of thousands of goroutines run at once; memory and switching costs stay low.
Practice Start a goroutine
Inside main, add a go func(){}() call and print goroutine started with fmt.Println.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
go func() {
fmt.Println("goroutine başladı")
}()
fmt.Println("goroutine başladı")
}Expected output
goroutine başladı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which keyword starts a goroutine?
- async
- go Correct answer
- thread
- spawn
Explanation: the go keyword. async is JavaScript, thread and spawn belong to other languages.
2 The goroutine keyword
To run a function in the background, put ____ before the call.
To run a function in the background, put go before the call.
Explanation: the go keyword starts a goroutine.
3 Match goroutine concepts
| Term | Meaning |
|---|---|
goroutine |
Lightweight thread |
go |
Start keyword |
G-M-P |
Scheduler model |
scheduler |
Dispatcher |