如何在 AppEngine 中使用 goroutine?

How to use goroutine inside AppEngine?

我正在使用 Cloud Endpoints 和 Go,我正在尝试使用 goroutine 以异步方式调用方法。

当我在本地 运行 以下代码时,我可以看到调试打印,但在服务器上似乎没有调用该方法。

我基本上是在尝试做

go doStuff()

return type 

AppEngine 的 Go 运行时支持 goroutines,引用自文档:Go Runtime Environment: Introduction:

The Go runtime environment for App Engine provides full support for goroutines, but not for parallel execution: goroutines are scheduled onto a single operating system thread.

问题是,当您的 HandleFunc() or Handler.ServeHTTP() returns, the AppEngine platform (and the http 包也一样时) 不会等待 处理函数启动的任何 goroutine 完成。

引用文档:Handling Requests: Responses:

App Engine calls the handler with a Request and a ResponseWriter, then waits for the handler to write to the ResponseWriter and return. When the handler returns, the data in the ResponseWriter's internal buffer is sent to the user.

您必须同步您的请求处理和 goroutine,并且仅在 goroutine 完成其工作后 return,例如:

func doStuff(done chan int) {
    // Do your stuff
    // and finally signal that you're done:
    done <- 0
}

func someHandler(w http.ResponseWriter, r *http.Request) {
    done := make(chan int)
    go doStuff(done)
    // Wait for the goroutine to complete:
    <-done
}