Home  >  Article  >  Backend Development  >  Will a Goroutine Launched in an HTTP Handler Always Finish After the Response is Sent?

Will a Goroutine Launched in an HTTP Handler Always Finish After the Response is Sent?

Barbara Streisand
Barbara StreisandOriginal
2024-11-25 17:27:13927browse

Will a Goroutine Launched in an HTTP Handler Always Finish After the Response is Sent?

Goroutine Execution within HTTP Handlers

Question:

In the provided example code, where a goroutine is initiated within an HTTP handler (HomeHandler), will the goroutine always complete execution, even after the server returns the response to the client?

Example Code:

package main

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

func worker() {
    fmt.Println("worker started")
    time.Sleep(time.Second * 10)
    fmt.Println("worker completed")
}

func HomeHandler(w http.ResponseWriter, r *http.Request) {
    go worker()
    w.Write([]byte("Hello, World!"))
}

func main() {
    http.HandleFunc("/home", HomeHandler)
    http.ListenAndServe(":8081", nil)
}

Answer:

Yes, the goroutine started in worker will complete its execution in all situations.

Goroutines are lightweight threads within a Go program and are not constrained by the execution of the main function or the HTTP handler. They continue to run concurrently unless they encounter errors or are explicitly terminated. In this case, the worker goroutine is started asynchronously, and the HomeHandler function returns immediately after writing the response to the client. Even after the handler function returns and the server sends the response, the worker goroutine continues to execute until it finishes its task of sleeping for 10 seconds and printing its completion message.

The only scenarios where a goroutine may not complete are:

  • If the main function exits and terminates the entire program.
  • If the program experiences a fatal error, such as running out of memory.

The above is the detailed content of Will a Goroutine Launched in an HTTP Handler Always Finish After the Response is Sent?. 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