Goroutine lifecycle
- Go course
- Expert
- Lesson 2/34
- 4 min
Learn the running, waiting and dead states of a goroutine.
Goroutine lifecycle
A goroutine goes through these states: runnable (in a queue, waiting to run) → running (running on an M+P) → waiting (waiting on a channel, lock, timer or network) → runnable again → finally dead.
ch := make(chan int)
go func() { ch <- 1 }() // runnable → running
v := <-ch // main waiting, then runnableA waiting goroutine releases the P; the P immediately runs another G.
Leaked goroutines
A goroutine waiting for an event that will never come stays waiting forever and never frees its memory; this is a goroutine leak. A typical cause is writing to a channel whose result nobody reads:
func ilk(urls []string) string {
ch := make(chan string) // unbuffered!
for _, u := range urls {
go func() { ch <- getir(u) }()
}
return <-ch // the others wait forever
}Fix: make(chan string, len(urls)) or cancellation with a context.
Practice First result without leaks
Write ilk(n int) int: start n goroutines, each sending its own index to a channel, and return the first one that arrives. Prevent the leak by creating the channel with capacity n. Print ilk(3) >= 0.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func ilk(n int) int {
ch := make(chan int, n)
for i := 0; i < n; i++ {
go func(i int) { ch <- i }(i)
}
return <-ch
}
func main() {
fmt.Println(ilk(3) >= 0)
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 A goroutine sending <code>ch <- 1</code> with no reader is in which state?
- waiting (on the channel) Correct answer
- running
- dead
- runnable
Explanation: On an unbuffered channel the send puts the goroutine into waiting until a receiver arrives, releasing the P.
2 Prevent the leak
ch := make(chan string, ____)
ch := make(chan string, len(urls))
Explanation: A buffer with room for every sender lets goroutines finish even when results go unread.
3 State and cause
| Term | Meaning |
|---|---|
runnable |
Waiting its turn in a queue |
running |
Running on a P |
waiting |
Waiting on channel/lock/network |
dead |
The function returned |