一种方法可能是:
上面的内容将帮助我找到已启动、正在循环或阻塞某些内容但有一段时间没有执行任何操作的 goroutine。例如,当 websocket 连接断开或主题被取消订阅时,本应死亡的 goroutine 但实际上并未死亡,基本上是僵尸。
问:有谁知道上述或类似的事情是否可能>
用这样的东西(未经测试)来检测你的代码,可能会起作用:
package gor
import (
"time"
"runtime"
"sync"
)
type GoroutineInfo struct {
lastActive time.Time
name string
startFile string
startLine int
}
var goroutinesMap = make(map[*GoroutineInfo]*GoroutineInfo)
var mtx = sync.Mutex{}
func Gor(f func()){
mtx.Lock()
_, file, line, ok := runtime.Caller(1)
if !ok {
file = "unknown"
line = 0
}
info := &GoroutineInfo{
lastActive: time.Now(),
startFile: file,
startLine: line,
}
goroutinesMap[info] = info
mtx.Unlock()
go func() {
var keepGoing = true;
go func() {
for keepGoing {
time.Sleep(time.Second*3)
mtx.Lock()
var inf = goroutinesMap[info]
inf.lastActive = time.Now()
mtx.Unlock()
}
}()
defer func() {
keepGoing = false;
}()
// call the original func
// when defer (above) is called, goroutine is done
f();
}()
}
像这样使用它:
gor.Gor(func(){
// runs in the custom goroutine wrapper
});