在http处理程序中执行Goroutine [英] Goroutine execution inside an http handler

查看:87
本文介绍了在http处理程序中执行Goroutine的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在http处理程序中启动goroutine,即使在返回响应之后它是否会完成?下面是一个示例代码:

 包主

导入(
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)
}

在上面的例子中,是否在所有情况下完成 worker goroutine?或者有没有什么特殊情况下它不会完成? 解决方案

是的,它会完成,没有什么能够阻止它。



main()返回阻止goroutine从外部完成 code>函数(这也意味着完成程序的执行,但这种情况在您的情况下不会发生)。以及其他导致不稳定状态的情况,如内存耗尽。


If I start a goroutine inside an http handler, is it going to complete even after returning the response ? Here is an 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)
}

In the above example, is that worker goroutine going to complete in all situations ? Or is there any special case when it is not going to complete?

解决方案

Yes, it will complete, there's nothing stopping it.

The only thing that stops goroutines to finish "from the outside" is returning from the main() function (which also means finishing the execution of your program, but this never happens in your case). And other circumstances which lead to unstable states like running out of memory.

这篇关于在http处理程序中执行Goroutine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆