-
Notifications
You must be signed in to change notification settings - Fork 1
/
tour-concurrency-5.ts
70 lines (60 loc) · 1.18 KB
/
tour-concurrency-5.ts
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
/*
// https://go.dev/tour/concurrency/5
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)
}
*/
import { Chan, RecvChan, SendChan } from '../chan';
import { select } from '../select';
async function fibonacci(c: SendChan<number>, quit: RecvChan<number>) {
let x = 0,
y = 1;
for (;;) {
let shouldReturn = false;
await select()
.send(c, x, () => {
[x, y] = [y, x + y];
})
.recv(quit, () => {
console.log('quit');
shouldReturn = true;
});
if (shouldReturn) {
return;
}
}
}
function main() {
const c = new Chan<number>();
const quit = new Chan<number>();
setImmediate(async () => {
for (let i = 0; i < 10; i++) {
console.log(await c.recv());
}
await quit.send(0);
});
fibonacci(c, quit);
}
main();