Skip to content

Instantly share code, notes, and snippets.

@sugilog
Created January 31, 2015 09:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sugilog/e9fb99c7e50d4e5dbe36 to your computer and use it in GitHub Desktop.
Save sugilog/e9fb99c7e50d4e5dbe36 to your computer and use it in GitHub Desktop.
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