gpt4 book ai didi

google-app-engine - 如何在 AppEngine 中使用 goroutine?

转载 作者:IT王子 更新时间:2023-10-29 01:42:41 25 4
gpt4 key购买 nike

我正在使用 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()Handler.ServeHTTP()返回时,AppEngine 平台(以及 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 完成其工作后才返回,例如:

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
}

关于google-app-engine - 如何在 AppEngine 中使用 goroutine?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30369661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com