From e98d57e6d10d4d2ba72364de869965c0599b7ef0 Mon Sep 17 00:00:00 2001 From: oscarzhou Date: Mon, 26 Apr 2021 20:37:35 +1200 Subject: [PATCH] basics: add more examples about how to use goroutine --- basics/default-select/main.go | 25 ++++++++++++++++++++++++ basics/{ => flow-control}/main.go | 0 basics/range-close/main.go | 25 ++++++++++++++++++++++++ basics/select/main.go | 32 +++++++++++++++++++++++++++++++ 4 files changed, 82 insertions(+) create mode 100644 basics/default-select/main.go rename basics/{ => flow-control}/main.go (100%) create mode 100644 basics/range-close/main.go create mode 100644 basics/select/main.go diff --git a/basics/default-select/main.go b/basics/default-select/main.go new file mode 100644 index 0000000..8508139 --- /dev/null +++ b/basics/default-select/main.go @@ -0,0 +1,25 @@ +package main + +import ( + "log" + "time" +) + +func main() { + tick := time.Tick(100 * time.Millisecond) + + boom := time.After(5000 * time.Millisecond) + + for { + select { + case <-tick: + log.Println("tick.") + case <-boom: + log.Println("boom") + return + default: + log.Println(" .") + time.Sleep(50 * time.Millisecond) + } + } +} diff --git a/basics/main.go b/basics/flow-control/main.go similarity index 100% rename from basics/main.go rename to basics/flow-control/main.go diff --git a/basics/range-close/main.go b/basics/range-close/main.go new file mode 100644 index 0000000..ec1c816 --- /dev/null +++ b/basics/range-close/main.go @@ -0,0 +1,25 @@ +package main + +import ( + "log" +) + +func fibonacci(n int, ch chan int) { + x, y := 0, 1 + for i := 0; i < n; i++ { + ch <- x + x, y = y, x+y + } + close(ch) +} + +func main() { + ch := make(chan int, 10) + + go fibonacci(cap(ch), ch) + for i := range ch { + log.Println(i) + } + + log.Println("Done") +} diff --git a/basics/select/main.go b/basics/select/main.go new file mode 100644 index 0000000..15ee813 --- /dev/null +++ b/basics/select/main.go @@ -0,0 +1,32 @@ +package main + +import "log" + +func fibonacci(ch, quit chan int) { + x, y := 0, 1 + for { + select { + case ch <- x: + x, y = y, x+y + case <-quit: + log.Println("quit") + return + } + } +} + +func main() { + ch := make(chan int, 10) + + quit := make(chan int) + + go func() { + for i := 0; i < cap(ch); i++ { + log.Println(<-ch) + + } + quit <- 0 + }() + + fibonacci(ch, quit) +}