我在第三方库中有一个我无法控制的阻塞操作.它可能会永远消失.所以我想设置一个超时.显而易见的方法是用通道和goroutine包装它,然后选择结果time.After.然而,问题是运行阻塞操作的goroutine可能会永远存在.
这是一个例子来说明这个http://repl.it/90o
有没有办法取消goroutine或收集垃圾?
如果我在一个http处理程序中启动一个goroutine,它是否会在返回响应后完成?这是一个示例代码:
package main
import (
"fmt"
"net/http"
"time"
)
func worker() {
fmt.Println("worker started")
time.Sleep(time.Second * 10)
fmt.Println("worker completed")
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
go worker()
w.Write([]byte("Hello, World!"))
}
func main() {
http.HandleFunc("/home", HomeHandler)
http.ListenAndServe(":8081", nil)
}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,workergoroutine是否会在所有情况下完成?或者是否有任何特殊情况无法完成?