1
1
package main
2
2
3
- import "fmt"
3
+ import (
4
+ "fmt"
5
+ "time"
6
+ )
4
7
5
8
func sum (nums []int , c chan int ) {
6
9
length := len (nums )
@@ -13,6 +16,32 @@ func sum(nums []int, c chan int) {
13
16
c <- sum
14
17
}
15
18
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
+
16
45
func main () {
17
46
18
47
nums := []int {
@@ -38,4 +67,58 @@ func main() {
38
67
39
68
fmt .Println ("first" , <- channel_v1 )
40
69
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
+
41
124
}
0 commit comments