Junior — Middle
How is a goroutine transitioned into a blocked state in Go?
sobes.tech AI
Answer from AI
In Go, a goroutine enters a blocked state when it is waiting for some event, such as input/output, receiving a value from a channel, releasing a mutex, or a timer. At this moment, the Go scheduler pauses the execution of this goroutine and switches to other ready-to-run goroutines.
For example, if a goroutine tries to read from a channel but there is no data in the channel, it blocks until another thread writes data into it:
ch := make(chan int)
go func() {
val := <-ch // blocks until a value arrives
fmt.Println(val)
}()
ch <- 42 // unblocks the goroutine
Thus, blocking a goroutine is a cooperative scheduling mechanism that allows efficient use of system resources without active waiting (busy waiting).