【问题标题】:Go program creating OS threads for every goroutine even though there are no syscalls即使没有系统调用,Go 程序也会为每个 goroutine 创建 OS 线程
【发布时间】:2014-10-21 12:14:03
【问题描述】:

我正在使用 go 1.3.3。 我在我的 Mac 上运行以下 go 程序,它是 10.9.2 Intel Core i7:

package main
import (
         "fmt"
         "sync"
)

func justprint(i int, wg *sync.WaitGroup) {
     for j := 0; j < 1000000; j++ {
          fmt.Printf("Printing %d\n", i)
     }
     wg.Done()
}

func main() {
     var wg sync.WaitGroup
     for i := 0; i < 5; i++ {
          wg.Add(1)
          go justprint(i, &wg)
     }
     wg.Wait()
     fmt.Println("Done!!")
}

如果我运行这个程序,我会在活动监视器中看到 8 个线程正在生成。在 goroutine justprint() 中没有系统调用,所以我期望在运行该程序时不会创建额外的线程,而不是任何 go 程序创建的默认线程。但是随着我增加 goroutine 调用的数量,操作系统线程也相应增加。谁能帮我理解为什么会这样?

【问题讨论】:

  • @CharlieTumahai Nah,打印到标准输出当然使用特殊的 outouts 指令!
  • 你是对的......我没有意识到。非常感谢您解决这个问题。

标签: go goroutine


【解决方案1】:

你确定它为每个 goroutine 创建一个线程吗?尝试将 goroutine 的数量增加到 1000。我敢打赌线程的数量保持不变。 Go 创建并管理多个线程来处理异步 I/O。

【讨论】:

    猜你喜欢
    • 2020-04-04
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多