Skip to content

Instantly share code, notes, and snippets.

@sugilog sugilog/sample.go
Created Jan 31, 2015

Embed
What would you like to do?
Channelsのselect
package main
import (
"fmt"
"time"
)
const CAP = 20
func main() {
callFibonacciWithDefault()
callFibonacciWithoutDefault()
}
func fibonacciWithDefault( c, c1, quit chan int ) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x + y
case <- quit:
fmt.Println( "quit" )
return
default:
// fmt.Println( "default" )
i, ok := <- c1
if ok {
fmt.Println( "start?", i )
time.Sleep( 100 * time.Millisecond )
}
}
}
}
func callFibonacciWithDefault() {
c := make( chan int )
quit := make( chan int )
c1 := make( chan int )
go func() {
c1 <- 1
close( c1 )
for i := 0; i < CAP; i++ {
fmt.Println( i, <-c )
}
quit <- 0
}()
fibonacciWithDefault( c, c1, quit )
}
func fibonacciWithoutDefault( c, quit chan int ) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x + y
case <- quit:
fmt.Println( "quit" )
return
}
}
}
func callFibonacciWithoutDefault() {
c := make( chan int )
quit := make( chan int )
go func() {
for i := 0; i < CAP; i++ {
fmt.Println( i, <-c )
}
quit <- 0
}()
fibonacciWithoutDefault( c, quit )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.