go - 为什么 golang 中的网络 IO 线程使用量会增加?

标签 go

我创建了一个测试程序来检查我对 Golang 如何处理网络 IO 的理解。 下面的程序创建了 1000 个 goroutine,并且在每个 goroutine 中,它将发出一个网络 IO 请求。

当我尝试监视正在使用的线程数时,它上升到 400 个线程。 我曾经使用top命令来监控,我的理解是对于网络io Golang使用netpoll(即async io)。

如果我的理解有误,请指正。

操作系统:macos High Sierra

Go版本:go1.11.2 darwin/amd64

package main

import (
    "encoding/json"
    "log"
    "net/http"
    "sync"
    "time"
)

func main() {
    timeout := time.Duration(5 * time.Second)
    client := http.Client{
        Timeout: timeout,
    }
    var wg sync.WaitGroup

    start := time.Now()
    for i := 0; i < 1000; i++ {
        wg.Add(1)
        go callAPI(&wg, client)
    }
    wg.Wait()
    log.Println(time.Since(start))
}

func callAPI(wg *sync.WaitGroup, client http.Client) {
    defer wg.Done()
    url := `JSON-API-URL-OF-YOUR-CHOICE` // Please enter a valid json api url.
    request, err := http.NewRequest("GET", url, nil)
    if err != nil {
        log.Fatalln(err)
    }

    resp, err := client.Do(request)
    if err != nil {
        log.Fatalln(err)
    }

    var result map[string]interface{}
    json.NewDecoder(resp.Body).Decode(&result)
    defer resp.Body.Close()

    log.Println(result)
}

最佳答案

当一个线程在系统 IO 调用上被阻塞时,Go 可能会创建一个新线程以允许其他 goroutine 继续运行。这有一个很好的解释:https://povilasv.me/go-scheduler/ :

Interesting things happen when your goroutine makes a blocking syscall. Blocking syscall will be intercepted, if there are Gs to run, runtime will detach the thread from the P and create a new OS thread (if idle thread doesn’t exist) to service that processor.

因此,不是拥有少量线程并利用 0% 的 CPU,因为所有线程都在等待阻塞系统调用返回,而是将这些线程放在一边并启动新线程,以便非阻塞 goroutine可以在等待阻塞系统调用返回时完成其工作。

关于go - 为什么 golang 中的网络 IO 线程使用量会增加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53983656/

相关文章:

go - 我应该如何在 Go 1.6 中使用 vendor?

angularjs - 在 AngularJS 中使用 Google Drive API 进行身份验证

go - 如何在事务回滚上添加一些操作

json - 如何在 Go 中设置自定义 json 响应结构

string - 是否可以针对反引号键入断言?

go - 用结构解码复杂的 JSON 广告

http - 转义http请求中的感叹号

process - 如何在golang中的exec.command中添加空格

go - 测试整数乘法的溢出

go - 一个通用的 golang 装饰器(要点需要澄清)