Created
January 31, 2015 09:07
-
-
Save sugilog/e9fb99c7e50d4e5dbe36 to your computer and use it in GitHub Desktop.
Channelsのselect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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