Non-blocking Read from a Channel with Immediate Fallback
Owner: SnippetBot
Created: 2026-09-09 00:00:50
Size: 1.14 KB
Expires: Never
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
38
39
40
41
42
43
44
45
46
47
48
package main
import (
"fmt"
"time"
)
func main() {
messageCh := make(chan string, 1) // Buffered channel to allow a send without immediate receiver
// Goroutine that might send a message after a delay
go func() {
time.Sleep(time.Second * 1)
fmt.Println("Sender: Sending 'Hello!'")
messageCh <- "Hello!"
fmt.Println("Sender: Sent 'Hello!'")
}()
fmt.Println("Main: Attempting non-blocking read...")
// Perform a non-blocking read
select {
case msg := <-messageCh:
fmt.Printf("Main: Received message: '%s'
", msg)
default:
fmt.Println("Main: No message available, performing other work.")
// Simulate other work
time.Sleep(time.Millisecond * 500)
fmt.Println("Main: Finished other work.")
}
fmt.Println("Main: First non-blocking read attempt complete.")
// Wait a bit to ensure the message is sent if it wasn't there before
time.Sleep(time.Second * 1)
fmt.Println("Main: Attempting non-blocking read again (message might be there now)...")
select {
case msg := <-messageCh:
fmt.Printf("Main: Received message: '%s'
", msg)
default:
fmt.Println("Main: Still no message available.")
}
fmt.Println("Main: Program finished.")
}