Performing Non-Blocking Reads and Writes on Go Channels
Owner: SnippetBot
Created: 2026-08-02 00:00:46
Size: 2.54 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"fmt"
"time"
)
func main() {
// Unbuffered channel
messageChannel := make(chan string)
// Buffered channel
bufferedChannel := make(chan int, 2)
fmt.Println("--- Non-blocking read from unbuffered channel ---")
select {
case msg := <-messageChannel:
fmt.Printf("Received message: %s
", msg)
default:
fmt.Println("No message available immediately (unbuffered channel).")
}
fmt.Println("
--- Non-blocking write to unbuffered channel ---")
select {
case messageChannel <- "hello":
fmt.Println("Sent message: hello")
default:
fmt.Println("Could not send message immediately (unbuffered channel, no receiver).")
}
// Start a receiver for the unbuffered channel
go func() {
time.Sleep(100 * time.Millisecond) // Simulate some delay
msg := <-messageChannel
fmt.Printf("Goroutine received: %s
", msg)
}()
// Try sending again after a short delay (receiver might be ready)
time.Sleep(50 * time.Millisecond)
fmt.Println("
--- Non-blocking write to unbuffered channel (retry with receiver) ---")
select {
case messageChannel <- "world":
fmt.Println("Sent message: world")
default:
fmt.Println("Could not send message immediately (unbuffered channel, receiver not ready yet).")
}
// Give time for the receiver goroutine to finish
time.Sleep(100 * time.Millisecond)
fmt.Println("
--- Non-blocking write to buffered channel ---")
select {
case bufferedChannel <- 1:
fmt.Println("Sent 1 to buffered channel.")
default:
fmt.Println("Buffered channel is full, could not send 1.")
}
select {
case bufferedChannel <- 2:
fmt.Println("Sent 2 to buffered channel.")
default:
fmt.Println("Buffered channel is full, could not send 2.")
}
select {
case bufferedChannel <- 3: // This will fail as capacity is 2
fmt.Println("Sent 3 to buffered channel.")
default:
fmt.Println("Buffered channel is full, could not send 3 (expected).")
}
fmt.Println("
--- Non-blocking read from buffered channel ---")
select {
case val := <-bufferedChannel:
fmt.Printf("Read %d from buffered channel.
", val)
default:
fmt.Println("Buffered channel is empty, no value to read.")
}
select {
case val := <-bufferedChannel:
fmt.Printf("Read %d from buffered channel.
", val)
default:
fmt.Println("Buffered channel is empty, no value to read.")
}
select { // This will now hit default
case val := <-bufferedChannel:
fmt.Printf("Read %d from buffered channel.
", val)
default:
fmt.Println("Buffered channel is empty, no value to read (expected).
")
}
close(messageChannel)
close(bufferedChannel)
fmt.Println("Main: Exiting.")
}