Created
June 19, 2021 03:08
-
-
Save jamesBan/ac319408d5d06621b20b637b439d5754 to your computer and use it in GitHub Desktop.
context timeout routine泄漏问题
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" | |
"golang.org/x/net/context" | |
"log" | |
"math/rand" | |
"runtime" | |
"time" | |
) | |
func job() error { | |
ctx, cancel := context.WithTimeout(context.Background(), time.Second) | |
defer cancel() | |
done := make(chan struct{}) | |
defer close(done) | |
go func() { | |
time.Sleep(time.Second * time.Duration(rand.Intn(5))) | |
//if _, ok := <- done; ok { | |
// done <- struct{}{} | |
//} | |
select { | |
case <-ctx.Done(): | |
log.Println("receive cancel signal ready to break") | |
return | |
default: | |
done <- struct{}{} | |
} | |
}() | |
select { | |
case <-done: | |
return nil | |
case <-ctx.Done(): | |
return ctx.Err() | |
} | |
} | |
func main() { | |
for i := 0; i < 50; i++ { | |
go func() { | |
fmt.Println(job()) | |
}() | |
} | |
for true { | |
time.Sleep(time.Second) | |
fmt.Println("current routine num:", runtime.NumGoroutine()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment