英文:
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使用
Request
和ResponseWriter
调用处理程序,然后等待处理程序写入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'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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论