Skip to content

Instantly share code, notes, and snippets.

@suzuki-shunsuke
Last active October 12, 2018 14:45
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 suzuki-shunsuke/3fd8291928e5d10fbe631ba1060f511c to your computer and use it in GitHub Desktop.
Save suzuki-shunsuke/3fd8291928e5d10fbe631ba1060f511c to your computer and use it in GitHub Desktop.
// 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")
}
// 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")
}
// 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