Created
June 1, 2019 01:29
-
-
Save evangwt/2e40f28944c6fff4fbbfa5cbc59758a8 to your computer and use it in GitHub Desktop.
go routine leak
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" | |
"log" | |
"runtime" | |
"strconv" | |
"strings" | |
"sync" | |
"time" | |
) | |
func main() { | |
log.Println("running") | |
printStack() | |
// wg := sync.WaitGroup{} | |
// wg.Add(2) | |
go func(wg *sync.WaitGroup) { | |
// defer wg.Done() | |
go func() { | |
for { | |
time.Sleep(1 * time.Second) | |
log.Println("sub 2: running") | |
} | |
}() | |
count := 1 | |
for { | |
time.Sleep(1 * time.Second) | |
log.Println("sub 1: running") | |
count++ | |
if count > 3 { | |
log.Println("sub 1: done") | |
printStack() | |
return | |
} | |
} | |
// }(&wg) | |
}(nil) | |
printStack() | |
//wg.Wait() | |
buf := make([]byte, 0, 0x1<<8) | |
fmt.Scan(&buf) | |
printStack() | |
log.Println("done") | |
} | |
func printStack() { | |
buf := make([]byte, 2<<20) | |
buf = buf[:runtime.Stack(buf, true)] | |
log.Printf("stack: %v", string(buf)) | |
for _, g := range strings.Split(string(buf), "\n\n") { | |
printGoroutineID(g) | |
} | |
} | |
func printGoroutineID(g string) { | |
sl := strings.SplitN(g, "\n", 2) | |
if len(sl) != 2 { | |
log.Printf("error parsing stack: %q", g) | |
} | |
h := strings.SplitN(sl[0], " ", 3) | |
if len(h) < 3 { | |
log.Printf("error parsing stack header: %q", sl[0]) | |
} | |
id, err := strconv.ParseUint(h[1], 10, 64) | |
if err != nil { | |
log.Printf("error parsing goroutine id: %s", err) | |
} | |
log.Printf("goroutine id: %v", id) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment