为什么在Linux中,golang运行Http服务会自动创建多个子进程?

时间:2016-09-09 12:55:56

标签: linux go process

这就是我以前做的测试代码

package main

import (
    "net/http"
    "time"
)

func main() {
    s := &http.Server{
        Addr:           ":9301",
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        MaxHeaderBytes: 1 << 20,
    }

    http.HandleFunc("/line/getList", Response)
    s.ListenAndServe()
}

func Response(w http.ResponseWriter, req *http.Request)  {

    w.Header().Set("Content-Type", "application/json; charset=utf-8")
    w.Header().Set("Connection", "keep-alive")
    w.WriteHeader(200)

    for i:= 0; i < 10000; i++ {
        w.Write([]byte("hello world"))
    }
}

以下是代码运行的情况

htop output showing a tree with nested apptest threads

系统是centos 6.5

这是正常的吗?如果不正常,如何限制golang自动创建大量的子进程?

1 个答案:

答案 0 :(得分:3)

您的htop程序正在显示线程,而不是进程。你看到的是Go自然创建的线程,用于运行goroutine并在内核中运行系统调用而不会阻塞。

You can control the number of threads created with the GOMAXPROCS environment variable.