Skip to content

Instantly share code, notes, and snippets.

@joeke80215
Created July 17, 2018 08:12
Show Gist options
  • Save joeke80215/cfb3f6ad977bdf290d9887e8be58b3ff to your computer and use it in GitHub Desktop.
Save joeke80215/cfb3f6ad977bdf290d9887e8be58b3ff to your computer and use it in GitHub Desktop.
package main
import (
"context"
"log"
"runtime"
"time"
)
var (
rCh chan int
blockCh chan struct{}
ctx context.Context
cancel context.CancelFunc
)
func init() {
runtime.GOMAXPROCS(runtime.NumCPU())
rCh = make(chan int, 0)
blockCh = make(chan struct{}, 0)
ctx, cancel = context.WithCancel(context.Background())
}
func r1(ctx context.Context) {
for {
select {
case <-ctx.Done():
log.Println("r1 exit")
runtime.Goexit()
case r := <-rCh:
log.Println("r1: ", r)
}
}
}
func r2(ctx context.Context) {
for {
select {
case <-ctx.Done():
log.Println("r2 exit")
runtime.Goexit()
case r := <-rCh:
log.Println("r2: ", r)
}
}
}
func sendValue(cancel context.CancelFunc) {
i := 0
for {
if i > 10 {
cancel()
} else {
rCh <- i
i++
}
log.Println("NumGoroutine: ", runtime.NumGoroutine())
time.Sleep(time.Duration(1) * time.Second)
}
}
func main() {
go r1(ctx)
go r2(ctx)
sendValue(cancel)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment