Skip to content

Instantly share code, notes, and snippets.

@masayoshi634
Created October 29, 2018 14:39
Show Gist options
  • Save masayoshi634/ced5e78f40d2fb0c62efcd4d6d3b1efd to your computer and use it in GitHub Desktop.
Save masayoshi634/ced5e78f40d2fb0c62efcd4d6d3b1efd to your computer and use it in GitHub Desktop.
package main
import (
"log"
"time"
)
func main() {
size := 100
for num := range FibonacciGenerator(size, false) {
log.Println(num)
}
// TimeOut処理 と ChannelのClose検知 と待ち時間中の処理
receiver := FibonacciGenerator(size, true)
timeout := time.After(time.Second)
for {
select {
case receive, ok := <-receiver:
if !ok {
log.Println("finish")
return
}
log.Println(receive)
case <-timeout:
log.Println("timeout")
return
default:
log.Println("wait")
time.Sleep(time.Duration(100) * time.Millisecond)
}
}
}
func FibonacciGenerator(size int, isDelay bool) <-chan int {
ch := make(chan int)
a := 0
b := 1
tmp := 0
go func() {
for i := 0; i < size; i++ {
ch <- b
tmp = b
b = a + b
a = tmp
if isDelay {
time.Sleep(time.Duration(b) * time.Millisecond)
}
}
close(ch)
}()
return ch
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment