0
0
Goprogramming~5 mins

Blocking behavior in Go

Choose your learning style9 modes available
Introduction

Blocking behavior means a program waits for something to finish before moving on. It helps control the order of tasks.

When you want to wait for a task to finish before starting another.
When reading data from a channel and you need to wait until data is available.
When you want to pause a program until a user input or event happens.
When synchronizing multiple parts of a program to work step-by-step.
When you want to make sure a resource is ready before using it.
Syntax
Go
value := <-channel
// This line waits (blocks) until a value is received from the channel

Receiving from a channel blocks the program until data is ready.

Sending to a channel also blocks if the channel is full or unbuffered.

Examples
The program waits at the receive line until some data is sent to ch.
Go
ch := make(chan int)

// This will block because no one sends data yet
value := <-ch
Buffered channels allow some sends without blocking until the buffer is full.
Go
ch := make(chan int, 1)

ch <- 5 // This does not block because channel has buffer
ch <- 10 // This blocks because buffer is full
This waits for the goroutine to finish by blocking on done channel receive.
Go
done := make(chan bool)
go func() {
    // Do some work
    done <- true // Signal completion
}()
<-done // Wait here until work is done
Sample Program

This program starts a goroutine that waits 2 seconds then sends a message. The main function waits (blocks) on the channel receive until the message arrives, then prints it.

Go
package main

import (
	"fmt"
	"time"
)

func main() {
	ch := make(chan string)

	go func() {
		time.Sleep(2 * time.Second)
		ch <- "Hello from goroutine"
	}()

	fmt.Println("Waiting for message...")
	msg := <-ch // This line blocks until message arrives
	fmt.Println("Received message:", msg)
}
OutputSuccess
Important Notes

Blocking is normal and useful in Go for synchronization.

Too much blocking can freeze your program, so use goroutines to run tasks concurrently.

Buffered channels can reduce blocking but need careful size management.

Summary

Blocking means waiting for something to finish before continuing.

Receiving or sending on channels can cause blocking in Go.

Use blocking to coordinate tasks and control program flow.