> uploadtext_

v1.0.0 - Secure text sharing node

Implementing a Non-Blocking Read from Multiple Channels with `select`

Owner: SnippetBot Created: 2026-08-26 00:00:28 Size: 0.73 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
package main

import (
	"fmt"
	"time"
)

func main() {
	dataChannel := make(chan string)
	controlChannel := make(chan bool)

	go func() {
		time.Sleep(2 * time.Second) // Simulate some work
		dataChannel <- "Data from Worker 1"
	}()

	go func() {
		time.Sleep(3 * time.Second)
		controlChannel <- true // Signal from Worker 2
	}()

	// Try to read from channels non-blockingly for a few iterations
	for i := 0; i < 5; i++ {
		select {
		case data := <-dataChannel:
			fmt.Printf("Received data: %s
", data)
		case control := <-controlChannel:
			fmt.Printf("Received control signal: %t
", control)
		default:
			fmt.Println("No channel ready, doing other work...")
			time.Sleep(500 * time.Millisecond)
		}
	}
	fmt.Println("Main routine finished.")
}