basics: add more examples about how to use goroutine
This commit is contained in:
parent
bdd898be69
commit
e98d57e6d1
25
basics/default-select/main.go
Normal file
25
basics/default-select/main.go
Normal 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)
|
||||
}
|
||||
}
|
||||
}
|
25
basics/range-close/main.go
Normal file
25
basics/range-close/main.go
Normal 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
32
basics/select/main.go
Normal 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)
|
||||
}
|
Loading…
Reference in New Issue
Block a user