Skip to content

Commit 9e0aa6b

Browse files
committed
Added examples of buffered channels, range and close for channels, select channels and defaults
1 parent c2631ba commit 9e0aa6b

File tree

1 file changed

+84
-1
lines changed
  • go_basics/goroutines/channels

1 file changed

+84
-1
lines changed

go_basics/goroutines/channels/main.go

+84-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package main
22

3-
import "fmt"
3+
import (
4+
"fmt"
5+
"time"
6+
)
47

58
func sum(nums []int, c chan int) {
69
length := len(nums)
@@ -13,6 +16,32 @@ func sum(nums []int, c chan int) {
1316
c <- sum
1417
}
1518

19+
func fibonacci(num int, c chan int) {
20+
x, y := 0, 1
21+
22+
for i := 0; i < num; i++ {
23+
c <- x
24+
x, y = y, x+y
25+
}
26+
27+
close(c)
28+
}
29+
30+
func fibonacciWithSelectOps(c, quit chan int) {
31+
32+
x, y := 0, 1
33+
34+
for {
35+
select {
36+
case c <- x:
37+
x, y = y, x+y
38+
case <-quit:
39+
fmt.Println("Quitting")
40+
return
41+
}
42+
}
43+
}
44+
1645
func main() {
1746

1847
nums := []int{
@@ -38,4 +67,58 @@ func main() {
3867

3968
fmt.Println("first", <-channel_v1)
4069
fmt.Println("second", <-channel_v1)
70+
71+
// range and close
72+
73+
var fiboChannel chan int = make(chan int, 10)
74+
75+
go fibonacci(cap(fiboChannel), fiboChannel)
76+
77+
// this will recieve values untill the channel is closed
78+
for i := range fiboChannel {
79+
fmt.Println(i)
80+
}
81+
82+
// ******************* END ************************* //
83+
84+
// select operations
85+
86+
// a select operation lets a goroutine wait on multiple communication operations
87+
88+
selectChan, quit := make(chan int, 15), make(chan int)
89+
90+
go func() {
91+
for i := 0; i < 10; i++ {
92+
fmt.Println("val", <-selectChan)
93+
}
94+
quit <- 0
95+
}()
96+
97+
fibonacciWithSelectOps(selectChan, quit)
98+
99+
// select statement with default
100+
101+
fmt.Println("\n")
102+
103+
timer := time.Tick(100 * time.Millisecond)
104+
boomer := time.After(500 * time.Millisecond)
105+
106+
// default runs if the channels are not ready (i.e the cases inside are not reade)
107+
108+
// here the timer runs after every 100 * milisecond delta
109+
// boom runs after every 500 miliseconds * delta
110+
// before these two are ready the default case runs and sleeps the programme for 25 * delta miliseconds (1/4 th of timer)
111+
for {
112+
select {
113+
case <-timer:
114+
fmt.Println("Ticking")
115+
case <-boomer:
116+
fmt.Println("Boom! The programme exploded")
117+
return
118+
default:
119+
fmt.Println("....")
120+
time.Sleep(25 * time.Millisecond)
121+
}
122+
}
123+
41124
}

0 commit comments

Comments
 (0)