Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Goroutines in Google App Engine (Standard Environment)?

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
}
like image 470
mattes Avatar asked Nov 28 '14 09:11

mattes


1 Answers

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)

like image 115
divan Avatar answered Sep 30 '22 04:09

divan