Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Goroutines with ListenAndServe increases performance?

Tags:

concurrency

go

I'm not very familiar with Go's routines but since I'm working with the router of net/http I saw a few times thatListenAndServe() is wrapped by a go routine.

A server needs to be able to handle multiple requests simultaneously out of the box to be efficient. So why are go routines as 'lightweight threads' used? Does the concurrency provide any advantages?

Here's an example by OpenShift

package main

import (
    "fmt"
    "net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello OpenShift!")
}

func main() {
    http.HandleFunc("/", helloHandler)

    go func() {
        fmt.Println("serving on 8080")
        err := http.ListenAndServe(":8080", nil)
        if err != nil {
            panic("ListenAndServe: " + err.Error())
        }
    }()

    go func() {
        fmt.Println("serving on 8888")
        err := http.ListenAndServe(":8888", nil)
        if err != nil {
            panic("ListenAndServe: " + err.Error())
        }
    }()
    select {}
}
like image 701
user3147268 Avatar asked May 27 '15 16:05

user3147268


People also ask

When should we use Goroutines?

Goroutines are useful when you want to do multiple things simultaneously. For example, if you have ten things you want to do at the same time, you can do each one on a separate goroutine, and wait for all of them to finish.

How many Goroutines can I run?

In the case of goroutines, since stack size can grow dynamically, you can spawn 1000 goroutines without a problem. As a goroutine starts with 8KB (2KB since Go 1.4) of stack space, most of them generally don't grow bigger than that.

Are Goroutines concurrent?

Goroutines are functions or methods that run concurrently with other functions or methods. Goroutines can be thought of as lightweight threads. The cost of creating a Goroutine is tiny when compared to a thread. Hence it's common for Go applications to have thousands of Goroutines running concurrently.

What are Goroutines and how do they work?

GoRoutines are a Golang wrapper on top of threads and managed by Go runtime rather than the operating system. Go runtime has the responsibility to assign or withdraw memory resources from Goroutines. A Goroutine is much like a thread to accomplish multiple tasks, but consumes fewer resources than OS threads.


2 Answers

http.ListenAndServe is a blocking call. If you want to go one doing more work (like making a second http.ListenAndServe call), you need to move it over to a separate goroutine. That's all they're doing here.

They're using select{} at the end to block the main goroutine, since all their calls to http.ListenAndServe are on other goroutines. If they didn't call select{}, the program would terminate because main() would return.

They could have achieved the same thing by dropping select{}, and removing the go func() wrapper around the last block of code. But I suspect they did it this way so that all the code is consistent.

But this has nothing to do with performance.

In the comments you provided some other examples that are similar. In the first example:

func main() {
    http.HandleFunc("/", responsehandler.Handler)
    go func() {
      http.ListenAndServe(":8888", nil)
    }()
    fileservice.NewWatcher()
}

This calls http.ListenAndServe and then calls fileservice.NewWatcher() (which blocks). If they hadn't wrapped the call in a goroutine, fileservice.NewWatcher() would never have been called.

The other two examples are a common piece of boilerplate:

func init() {
    go func() {
        log.Println(http.ListenAndServe("localhost:6060", nil))
    }()
}

This turns on the debug profiler web server. Again, it's a goroutine so that calling init returns immediately rather than blocking. This particular case allows the caller to just import _ "profiling" and "magically" get the debug profiler web server.

like image 112
Rob Napier Avatar answered Oct 10 '22 18:10

Rob Napier


No it does not have any special benefits beside being "run in the background".

like image 30
Volker Avatar answered Oct 10 '22 19:10

Volker