Home  >  Article  >  Backend Development  >  Can Goroutines Outlive HTTP Requests in Google App Engine (Standard Environment)?

Can Goroutines Outlive HTTP Requests in Google App Engine (Standard Environment)?

DDD
DDDOriginal
2024-10-29 00:36:30878browse

Can Goroutines Outlive HTTP Requests in Google App Engine (Standard Environment)?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn