Can I use Goroutines in Google App Engine (Standar

2020-02-26 09:19发布

The following example seems to work, but is it safe to use? My goal is to do some very light background processing (whereas an actual task queue job feels too heavy).

func MyHandler(w http.ResponseWriter, r *http.Request) {

  go func() {
    // do something ...
  }() 

  return // 200
}

2条回答
成全新的幸福
2楼-- · 2020-02-26 10:00

Goroutines that outlive the request are not supported, but you can use runtime.RunInBackground to execute code in a background goroutine:

func MyHandler(w http.ResponseWriter, r *http.Request) {

  err := runtime.RunInBackground(c, func(c appengine.Context) {
    // do something...
  })

  return // 200
}

The provided function will be invoked with a background context that is distinct from (and may outlast) the provided context. Note that there is a limit of 10 simultaneous background requests per instance. Here is another example.

Please note that Goroutines that live within the context of a request, are supported though:

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. This single-thread restriction may be lifted in future versions. Multiple requests may be handled concurrently by a given instance; that means that if one request is, say, waiting for a datastore API call, another request may be processed by the same instance. (Source)

查看更多
Root(大扎)
3楼-- · 2020-02-26 10:04

Just remember, folks, there is a world of difference between concurrency and parallel operation. This stumped me for a while (still does sometimes). See what Rob Pike says: https://www.youtube.com/watch?v=oV9rvDllKEg

In other words, yes, AppEngine can handle goroutines -- this is not being parallel. This is running the code the most efficient way possible and is a precursor to being able to run the code in parallel...

查看更多
登录 后发表回答