github.com/aykevl/tinygo@v0.5.0/testdata/channel.go (about) 1 package main 2 3 import "time" 4 5 func main() { 6 ch := make(chan int) 7 println("len, cap of channel:", len(ch), cap(ch)) 8 go sender(ch) 9 10 n, ok := <-ch 11 println("recv from open channel:", n, ok) 12 13 for n := range ch { 14 if n == 6 { 15 time.Sleep(time.Microsecond) 16 } 17 println("received num:", n) 18 } 19 20 n, ok = <-ch 21 println("recv from closed channel:", n, ok) 22 23 // Test multi-sender. 24 ch = make(chan int) 25 go fastsender(ch) 26 go fastsender(ch) 27 go fastsender(ch) 28 slowreceiver(ch) 29 30 // Test multi-receiver. 31 ch = make(chan int) 32 go fastreceiver(ch) 33 go fastreceiver(ch) 34 go fastreceiver(ch) 35 slowsender(ch) 36 37 // Test iterator style channel. 38 ch = make(chan int) 39 go iterator(ch, 100) 40 sum := 0 41 for i := range ch { 42 sum += i 43 } 44 println("sum(100):", sum) 45 46 // Test select 47 go selectDeadlock() 48 go selectNoOp() 49 50 // Allow goroutines to exit. 51 time.Sleep(time.Microsecond) 52 } 53 54 func sender(ch chan int) { 55 for i := 1; i <= 8; i++ { 56 if i == 4 { 57 time.Sleep(time.Microsecond) 58 println("slept") 59 } 60 ch <- i 61 } 62 close(ch) 63 } 64 65 func fastsender(ch chan int) { 66 ch <- 10 67 ch <- 11 68 } 69 70 func slowreceiver(ch chan int) { 71 for i := 0; i < 6; i++ { 72 n := <-ch 73 println("got n:", n) 74 time.Sleep(time.Microsecond) 75 } 76 } 77 78 func slowsender(ch chan int) { 79 for n := 0; n < 6; n++ { 80 time.Sleep(time.Microsecond) 81 ch <- 12 + n 82 } 83 } 84 85 func fastreceiver(ch chan int) { 86 sum := 0 87 for i := 0; i < 2; i++ { 88 n := <-ch 89 sum += n 90 } 91 println("sum:", sum) 92 } 93 94 func iterator(ch chan int, top int) { 95 for i := 0; i < top; i++ { 96 ch <- i 97 } 98 close(ch) 99 } 100 101 func selectDeadlock() { 102 println("deadlocking") 103 select {} 104 println("unreachable") 105 } 106 107 func selectNoOp() { 108 println("select no-op") 109 select { 110 default: 111 } 112 println("after no-op") 113 }