[英]Cancel go func()
假設我有一個golang函數,它類似於:
conn, _ := ln.Accept()
r := bufio.NewReader(conn)
func waiter(r *bufio.Reader) {
r.ReadString('\n')
}
go waiter(r)
time.Sleep(time.Second)
fmt.Println("hello")
我有什么辦法可以取消服務員,這樣它就不會掛在等待字符串輸入(如果它永遠不會出現)? 問題是bufio讀取器正在阻塞,我想讓它在置頂器上等待兩秒鍾,如果它沒有將任何數據讀入緩沖區以逃脫goroutine。
Conn
接口提供了一種SetReadDeadline
方法來在特定時間中斷SetReadDeadline
操作:
for {
// Set a deadline for reading. Read operation will fail if no data
// is received after deadline.
conn.SetReadDeadline(time.Now().Add(timeoutDuration))
// Read tokens delimited by newline
bytes, err := bufReader.ReadBytes('\n')
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%s", bytes)
}
http://www.mrleong.net/post/130329994134/go-tcp-connection-listening-and-timeout
編輯:上下文不能執行任何阻止讀取功能的操作,這不是該問題的正確解決方案。 在這種情況下,最好為連接設置空閑超時。
您可以使用context
包來控制goroutine。 上下文主要用於停止goroutine,以防它被取消,超時等。要使用它,您必須再接收一個參數ctx context
,並在goroutine中運行select。
Godoc的示例:
package main
import (
"context"
"fmt"
"time"
)
func main() {
// Pass a context with a timeout to tell a blocking function that it
// should abandon its work after the timeout elapses.
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
select {
case <-time.After(1 * time.Second):
fmt.Println("overslept")
case <-ctx.Done():
fmt.Println(ctx.Err()) // prints "context deadline exceeded"
}
}
在官方博客文章中了解有關上下文用例的更多信息: https : //blog.golang.org/context
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.