~kotrunga/a-tour-of-go

a-tour-of-go/concurrency/3.5_select.go -rw-r--r-- 577 bytes View raw
b3f98925kotrunga remove .DS_Store file 8 months ago
                                                                                
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
/*
	Notes 3.5

	"The select statement lets a goroutine wait on multiple communication operations.
	A select blocks until one of its cases can run, then it executes that case.
	It chooses one at random if multiple are ready."
*/

package main

import "fmt"

func fibonacci(c, quit chan int) {
	x, y := 0, 1
	for {
		select {
		case c <- x:
			x, y = y, x+y
		case <- quit:
			fmt.Println("quit")
			return
		}
	}
}

func main() {
	c := make(chan int)
	quit := make(chan int)
	go func() {
		for i := 0; i < 10; i++ {
			fmt.Println(<-c)
		}
		quit <- 0
	}()
	fibonacci(c, quit)
}