Back to Blog

Non-Blocking Channel Operations - Go Tutorial for Beginners #26

Sandy LaneSandy Lane

Video: Non-Blocking Channel Operations - Go Tutorial for Beginners #26 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Non-Blocking Channel Operations in Go

In Go, the select statement allows you to wait on multiple channel operations simultaneously, enabling powerful concurrency patterns. This tutorial demonstrates how to perform non-blocking channel operations using a default case, implement timeouts with time.After, and continuously process channels within loops.

Code

package main

import (
  "fmt"
  "time"
)

func main() {
  ch1 := make(chan string)
  ch2 := make(chan string)

  // Simulate sending data after some time
  go func() {
    time.Sleep(2 * time.Second)
    ch1 <- "message from ch1"
  }()
  go func() {
    time.Sleep(1 * time.Second)
    ch2 <- "message from ch2"
  }()

  timeout := time.After(3 * time.Second)

  for {
    select {
    case msg1 := <-ch1:
      fmt.Println("Received:", msg1)
    case msg2 := <-ch2:
      fmt.Println("Received:", msg2)
    case <-timeout:
      fmt.Println("Timeout reached, exiting")
      return
    default:
      // Non-blocking: no channel is ready, do other work
      fmt.Println("No messages yet, doing other work")
      time.Sleep(500 * time.Millisecond)
    }
  }
}

Key Points

  • The select statement lets you wait on multiple channel operations simultaneously.
  • Including a default case makes the select non-blocking, allowing the program to continue if no channels are ready.
  • time.After can be used in a select to implement timeouts for channel operations.
  • Using select inside loops enables continuous processing of incoming messages and other tasks.