Can Goroutines Outlive HTTP Requests in Google App Engine (Standard Environment)?
In Google App Engine's Standard Environment, it may seem possible to create goroutines that continue running after the HTTP request has been handled. However, this approach can lead to issues:
func MyHandler(w http.ResponseWriter, r *http.Request) { go func() { // do something ... }() return // 200 }
Answer:
Goroutines that outlive the request are not supported in App Engine's Standard Environment. Instead, use runtime.RunInBackground to execute code in a background goroutine. The provided function will receive a background context that is distinct from the request context. It is important to note that there is a limit of 10 simultaneous background requests per instance.
func MyHandler(w http.ResponseWriter, r *http.Request) { err := runtime.RunInBackground(c, func(c appengine.Context) { // do something... }) return // 200 }
Alternatively, goroutines that live within the context of a request are supported. However, App Engine's runtime environment only supports goroutines on a single operating system thread, so no parallel execution will occur.
The above is the detailed content of Can Goroutines Outlive HTTP Requests in Google App Engine (Standard Environment)?. For more information, please follow other related articles on the PHP Chinese website!