basics: add more examples about how to use goroutine

This commit is contained in:
oscarzhou 2021-04-26 20:37:35 +12:00
parent bdd898be69
commit e98d57e6d1
4 changed files with 82 additions and 0 deletions

View File

@ -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)
}
}
}

View File

@ -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")
}

32
basics/select/main.go Normal file
View File

@ -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)
}