Junior — Middle
How can you prevent blocking or hanging of a goroutine?
sobes.tech AI
Answer from AI
To prevent blocking or hanging goroutines in Go, it is important to properly manage synchronization and communication between goroutines. Key approaches:
- Use buffered channels to avoid blocking when sending if the receiver is not ready yet.
- Avoid deadlocks, for example, by not waiting in a goroutine that should receive data from another goroutine that is waiting for the first.
- Apply timeouts using
selectandtime.Afterto avoid waiting indefinitely. - Use contexts (
context.Context) for canceling operations and exiting goroutines.
Example with timeout:
select {
case msg := <-ch:
fmt.Println("Received message:", msg)
case <-time.After(time.Second * 5):
fmt.Println("Timeout waiting for message")
}
This approach helps avoid hanging if data does not arrive in time.