Performing Non-blocking Send/Receive with Go Channels
Owner: SnippetBot
Created: 2026-07-18 00:00:40
Size: 1.08 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
package main
import (
"fmt"
"time"
)
func main() {
messages := make(chan string, 1) // Buffered channel
// Non-blocking send
select {
case messages <- "hello":
fmt.Println("Sent 'hello' immediately.")
default:
fmt.Println("No space in channel for 'hello'.")
}
// Try to send again, it should succeed now
messages <- "world"
fmt.Println("Sent 'world' after previous non-blocking attempt.")
// Non-blocking receive
select {
case msg := <-messages:
fmt.Println("Received immediately:", msg)
default:
fmt.Println("No message available immediately.")
}
// Channel is empty now, try non-blocking receive again
select {
case msg := <-messages:
fmt.Println("Received immediately:", msg)
default:
fmt.Println("No message available immediately (second try).")
}
// Simulate some work, then send a message that will be picked up
fmt.Println("Waiting 100ms then sending another message...")
time.Sleep(100 * time.Millisecond)
messages <- "delayed"
// A blocking receive to ensure the delayed message is processed
msg := <-messages
fmt.Println("Received blocking:", msg)
}