-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconcurrency.go
93 lines (80 loc) · 1.53 KB
/
concurrency.go
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
package main
import (
"fmt"
"math/rand/v2"
"strconv"
"time"
)
func main() {
for i := 0; i < 10; i++ {
go sayHi()
}
sayHi()
fmt.Println("Finished?!")
time.Sleep(1 * time.Second)
fmt.Println("Finished after waiting")
s := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(s[:len(s)/2], c)
go sum(s[len(s)/2:], c)
x, y := <-c, <-c // receive from c
fmt.Println("x:", x, "-- y:", y, "-- x+y:", x+y)
// Let's limit the channel to 2 values
ch := make(chan int, 2)
ch <- 1
ch <- 2
// Uncomment the below and see what happens
// ch <- 3
fmt.Println("channel:", <-ch)
fmt.Println("channel:", <-ch)
// What if you want to continuously read from a
// channel until it's finished sending?
c = make(chan int, 10)
go fibonacci(cap(c), c)
for i := range c {
fmt.Println(i)
}
fmt.Println("Done!")
// Selecting channels is good for graceful shutdown
c = make(chan int)
quit := make(chan int)
go func() {
for i := 0; i < 10; i++ {
fmt.Println(<-c)
}
quit <- 0
}()
fibonacciWithQuit(c, quit)
}
func sayHi() {
randomWait := rand.IntN(1000)
time.Sleep(time.Duration(randomWait))
fmt.Println("Hi after", strconv.Itoa(randomWait)+"!")
}
func sum(s []int, c chan int) {
sum := 0
for _, v := range s {
sum += v
}
c <- sum // send sum to c
}
func fibonacci(n int, c chan int) {
x, y := 0, 1
for i := 0; i < n; i++ {
c <- x
x, y = y, x+y
}
close(c)
}
func fibonacciWithQuit(c, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x+y
case <-quit:
fmt.Println("quit")
return
}
}
}