15

I thought I'd found an easy way to return an http response immediately then do some work in the background without blocking. However, this doesn't work.

func MyHandler(w http.ResponseWriter, r *http.Request) {
    //handle form values
    go doSomeBackgroundWork() // this will take 2 or 3 seconds
    w.WriteHeader(http.StatusOK)
}

It works the first time--the response is returned immediately and the background work starts. However, any further requests hang until the background goroutine completes. Is there a better way to do this, that doesn't involve setting up a message queue and a separate background process.

2
  • It was actually just a test function doing some arithmetic, but apparently you were correct. GOMAXPROCS was set to whatever the default was, apparently 1. When I upped it to 2 it works fine. Thanks--if you want to answer this, I'll accept your answer. Aug 17, 2013 at 21:05
  • 1
    Minor note, but you probably want http.StatusAccepted there instead of http.StatusOK – 200 implies you've serviced the request. 202 tells the client that you intend to service the request, but you've not necessarily done so yet. 204 (http.StatusNoContent) is also sometimes acceptable, but I probably wouldn't use it in this case.
    – Dustin
    Aug 18, 2013 at 22:37

2 Answers 2

20

I know this question was posted 4 years ago, but I hope someone can find this useful.

Here is a way to do that

There are something called worker pool https://gobyexample.com/worker-pools Using go routines and channels

But in the following code I adapt it to a handler. (Consider for simplicity I'm ignoring the errors and I'm using jobs as global variable)

package main

import (
    "fmt"
    "net/http"
    "time"
)

var jobs chan int

func worker(jobs <-chan int) {
    fmt.Println("Register the worker")
    for i := range jobs {
        fmt.Println("worker processing job", i)
        time.Sleep(time.Second * 5)
    }
}

func handler(w http.ResponseWriter, r *http.Request) {
    jobs <- 1
    fmt.Fprintln(w, "hello world")
}

func main() {
    jobs = make(chan int, 100)
    go worker(jobs)

    http.HandleFunc("/request", handler)
    http.ListenAndServe(":9090", nil)
}

The explanation:

main()

  • Runs the worker in background using a go routine
  • Start the service with my handler
  • note that the worker in this moment is ready to receive a job

worker()

  • it is a go routine that receives a channel
  • the for loop never ends because the channel is never closed
  • when a the channel contain a job, do some work (e.g. waits for 5 seconds)

handler()

  • writes to the channel to active a job
  • immediately returns printing "hello world" to the page

the cool thing is that you can send as many requests you want and because this scenario only contains 1 worker. the next request will wait until the previous one finished.

This is awesome Go!

14

Go multiplexes goroutines onto the available threads which is determined by the GOMAXPROCS environment setting. As a result if this is set to 1 then a single goroutine can hog the single thread Go has available to it until it yields control back to the Go runtime. More than likely doSomeBackgroundWork is hogging all the time on a single thread which is preventing the http handler from getting scheduled.

There are a number of ways to fix this.

First, as a general rule when using goroutines, you should set GOMAXPROCS to the number of CPUs your system has or to whichever is bigger.

Second, you can yield control in a goroutine by doing any of the following:

  • runtime.Gosched()
  • ch <- foo
  • foo := <-ch
  • select { ... }
  • mutex.Lock()
  • mutex.Unlock()

All of these will yield back to the Go runtime scheduler giving other goroutines a chance to work.

4
  • 4
    Note that in development right now (in go tip) is a version of the scheduler which will preempt goroutines on any function call, not just the list above. This is expected to land in go 1.2. Aug 18, 2013 at 10:07
  • @NickCraig-Wood could you link to a source? I just tried to compile Go from the development tip, then compile a program with it and the behavior looked the same.
    – justinas
    Aug 18, 2013 at 13:13
  • 1
    It preempts on function calls not in the middle of the function so tip won't fix your particular problem yet. Aug 18, 2013 at 13:46
  • @JeremyWall please check my recent post. Aug 31, 2017 at 21:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.