Skip to content

Commit 5c11aa5

Browse files
committed
Added buffered channels with select
1 parent 053c961 commit 5c11aa5

File tree

1 file changed

+25
-14
lines changed

1 file changed

+25
-14
lines changed

select.go

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,42 +5,53 @@ import (
55
"time"
66
)
77

8-
// The select statement is used to listen for data coming from multiple channels concurrently, but the crucial aspect is the concurrent (or asynchronous) nature.
9-
// Especially when multiple tasks are being performed, using the select statement allows simultaneous access to data from channels and optimizes the processing time of the program.
10-
11-
// For instance, when waiting for data from the network or different threads of execution, it enables the main thread to continue doing other tasks while waiting for data from channels.
12-
// Instead of waiting idly until data arrives from any channel, select concurrently monitors multiple channels and acts accordingly when data arrives.
13-
14-
// The main thread waits until data is received from any of the channels being listened to with the select statement. However, it can also continue with other tasks,
15-
// execute other threads of execution, or perform different operations.
16-
17-
// This feature allows programs to monitor and manage various tasks concurrently, preventing the program from blocking in unexpected situations.
18-
// The use of select is highly beneficial in scenarios involving asynchronous operations or listening for data from various sources.
19-
208
func SelectExample() {
219
fmt.Println("--------------------------")
2210
channel3 := make(chan string)
2311
channel4 := make(chan string)
2412

13+
charChannel := make(chan string, 5)
14+
2515
go goRoutine3(channel3)
2616
go goRoutine4(channel4)
2717

18+
go fillBufferedChannel(charChannel)
19+
2820
select {
2921
case msg1 := <-channel3:
3022
fmt.Println("Received from Channel 3:", msg1)
3123
case msg2 := <-channel4:
3224
fmt.Println("Received from Channel 4:", msg2)
3325
}
3426

27+
var result string
28+
for i := 0; i < 5; i++ {
29+
select {
30+
case char := <-charChannel:
31+
result += char
32+
}
33+
}
34+
35+
fmt.Println("Received:", result)
3536
fmt.Println("Hello From Select!")
3637
}
3738

3839
func goRoutine3(c chan string) {
39-
time.Sleep(1 * time.Second)
40+
time.Sleep(4 * time.Second)
4041
c <- "3"
4142
}
4243

4344
func goRoutine4(c chan string) {
44-
time.Sleep(1 * time.Second)
45+
time.Sleep(4 * time.Second)
4546
c <- "4"
4647
}
48+
49+
func fillBufferedChannel(c chan string) {
50+
chars := []string{"e", "r", "d", "e", "m"}
51+
52+
for _, v := range chars {
53+
c <- v
54+
}
55+
56+
close(c)
57+
}

0 commit comments

Comments
 (0)