How to use goroutine inside AppEngine?

huangapple go评论75阅读模式
英文:

How to use goroutine inside AppEngine?

问题

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

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

我基本上想要做的是:

go doStuff()

返回类型
英文:

I'm using Cloud Endpoints and Go and I'm trying to call a method in asynchronous way by using a goroutine.

When I'm running the following code locally I can see the debug prints but on the server it looks like the method did not get called.

I'm basically trying to do

go doStuff()

return type 

答案1

得分: 2

AppEngine的Go运行时支持goroutines,引用文档中的说明:

App Engine的Go运行时环境完全支持goroutines,但不支持并行执行:goroutines会被调度到单个操作系统线程上。

问题在于,当你的HandleFunc()Handler.ServeHTTP()返回时,AppEngine平台(以及http包)不会等待由处理函数启动的任何goroutine完成。

引用文档中的说明:处理请求:响应

App Engine使用RequestResponseWriter调用处理程序,然后等待处理程序写入ResponseWriter并返回。当处理程序返回时,ResponseWriter的内部缓冲区中的数据将发送给用户。

你需要同步你的请求处理和goroutine,并且只有在goroutine完成工作后才返回,例如:

func doStuff(done chan int) {
    // 做你的事情
    // 最后发出完成信号:
    done <- 0
}

func someHandler(w http.ResponseWriter, r *http.Request) {
    done := make(chan int)
    go doStuff(done)
    // 等待goroutine完成:
    <-done
}
英文:

The Go runtime for AppEngine supports goroutines, quoting from the doc: 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.

The problem is that when your HandleFunc() or Handler.ServeHTTP() returns, the AppEngine platform (and the http package too) does not wait for any goroutines started by the handler function to complete.

Quoting from the doc: 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.

You have to synchronize your request handling and goroutine, and only return once the goroutine has completed its work, for example:

func doStuff(done chan int) {
    // Do your stuff
    // and finally signal that you&#39;re done:
    done &lt;- 0
}

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

huangapple
  • 本文由 发表于 2015年5月21日 17:24:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/30369661.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定