假設你有這樣的結構:ch := make(chan string)errCh := make(chan error)go func() { line, _, err := bufio.NewReader(r).ReadLine() if err != nil { errCh <- err } else { ch <- string(line) }}()select {case err := <-errCh: return "", errcase line := <-ch: return line, nilcase <-time.After(5 * time.Second): return "", TimeoutError}在 5 秒超時的情況下,goroutine 會掛起,直到 ReadLine 返回,這可能永遠不會發生。我的項目是一個長期運行的服務器,所以我不想要卡住的 goroutines 的積累。
1 回答

Smart貓小萌
TA貢獻1911條經驗 獲得超7個贊
ReadLine 在進程退出或方法讀取一行之前不會返回。管道沒有截止日期或超時機制。
如果對 ReadLine 的調用在超時后返回,goroutine 將阻塞。這可以通過使用緩沖通道來解決:
ch := make(chan string, 1)
errCh := make(chan error, 1)
應用程序應該調用Wait來清理與命令關聯的資源。goroutine 是調用它的好地方:
go func() {
line, _, err := bufio.NewReader(r).ReadLine()
if err != nil {
errCh <- err
} else {
ch <- string(line)
}
cmd.Wait() // <-- add this line
}()
這將導致 goroutine 阻塞,而這正是您試圖避免的。另一種方法是應用程序為每個命令泄漏資源。
- 1 回答
- 0 關注
- 183 瀏覽
添加回答
舉報
0/150
提交
取消