面试题答案
一键面试- 常见方式:
- 使用
context.Context
和超时机制。
- 使用
- 基本原理:
- 在启动
Goroutine
时传入一个带有超时的context.Context
。例如使用context.WithTimeout
函数创建一个带有指定超时时间的context
。Goroutine
内部在执行关键操作时,定期检查context
的Done
通道是否关闭。如果在操作过程中context
的Done
通道关闭,说明已经超时,也就意味着Goroutine
可能处于卡住状态,此时Goroutine
可以进行相应的清理操作并退出。如下示例代码:
- 在启动
package main
import (
"context"
"fmt"
"time"
)
func worker(ctx context.Context) {
select {
case <-ctx.Done():
fmt.Println("Goroutine detected as potentially stuck, exiting due to timeout")
return
case <-time.After(2 * time.Second):
fmt.Println("Goroutine completed normal operation")
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
go worker(ctx)
time.Sleep(3 * time.Second)
}
在上述代码中,worker
函数中的select
语句会等待ctx.Done()
通道关闭(即超时)或者time.After(2 * time.Second)
这个定时器到期。如果ctx.Done()
通道先关闭,就可以认为Goroutine
可能卡住了。