Last active
October 12, 2018 14:45
-
-
Save suzuki-shunsuke/3fd8291928e5d10fbe631ba1060f511c to your computer and use it in GitHub Desktop.
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
// https://play.golang.org/p/jUzWcBiO4xJ | |
// Output: | |
// B 0 | |
// A 0 | |
// end | |
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func funcA(a chan int) { | |
go funcB(a) | |
select { | |
case i := <- a: | |
fmt.Println("A", i) | |
} | |
} | |
func funcB(a chan int) { | |
select { | |
case i := <- a: | |
fmt.Println("B", i) | |
} | |
} | |
func main() { | |
a := make(chan int) | |
go funcA(a) | |
time.Sleep(3 * time.Second) | |
close(a) | |
time.Sleep(1 * time.Second) | |
fmt.Println("end") | |
} |
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
// https://play.golang.org/p/HCVfN1tkLQO | |
// Output: | |
// A 3 | |
// end | |
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func funcA(a chan int) { | |
go funcB(a) | |
select { | |
case i := <- a: | |
fmt.Println("A", i) | |
} | |
} | |
func funcB(a chan int) { | |
select { | |
case i := <- a: | |
fmt.Println("B", i) | |
} | |
} | |
func main() { | |
a := make(chan int) | |
go funcA(a) | |
time.Sleep(3 * time.Second) | |
a <- 3 | |
time.Sleep(1 * time.Second) | |
fmt.Println("end") | |
} |
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
// https://play.golang.org/p/DsHHxVMMGM1 | |
// Output: | |
// B canceled | |
// A canceled | |
// end | |
package main | |
import ( | |
"context" | |
"fmt" | |
"time" | |
) | |
func funcA(ctx context.Context) { | |
go funcB(ctx) | |
select { | |
case <- ctx.Done(): | |
fmt.Println("A canceled") | |
} | |
} | |
func funcB(ctx context.Context) { | |
select { | |
case <- ctx.Done(): | |
fmt.Println("B canceled") | |
} | |
} | |
func main() { | |
ctx, cancel := context.WithCancel(context.Background()) | |
go funcA(ctx) | |
time.Sleep(3 * time.Second) | |
cancel() | |
time.Sleep(1 * time.Second) | |
fmt.Println("end") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment