dsepcxw181184853 2014-10-17 11:38
浏览 21

Go程序中的OS线程

I am using go 1.3.3. I am trying to understand when Go spawns new threads. I have the following two Go programs:

Program 1:

package main

func main() {
     for ;; {
     }
}

Program 2:

package main
import (
         "sync"
)

func justrun(wg *sync.WaitGroup) {
     for ;; {
     }
     wg.Done()
}

func main() {
     var wg sync.WaitGroup
     go justrun(&wg)
     wg.Wait()
}

In the activity Monitor I see that for Program 1 there are 2 threads and for Program 2 there are 3 threads. I have multiple questions:

  1. In Program 1 what are these 2 threads. I guess one is for "main", but what is the other one for?
  2. In Program 2, once i introduce wg.Wait() the number of threads became 3. I was predicting Program 2 to use the same number of threads as Program 1. My understanding is that assume that main() is running on a thread M1 with context P1. The goroutine will go into the runqueue of P1. I read somewhere that all primitives in sync package do not cause the goroutine to use a thread when it gets blocked because of them. If this is the case, then goroutine should run concurrently with main in P1 context and on M1 and there should be no need of a new thread. Is wg.Wait() a thread blocking call?

Any help is appreciated.

  • 写回答

1条回答 默认 最新

  • doudi7570 2014-10-17 14:43
    关注

    The rules are that go will spawn exactly GOMAXPROCS threads for user-level code. From the runtime documentation:

    The GOMAXPROCS variable limits the number of operating system threads that can execute user-level Go code simultaneously.

    But note:

    There is no limit to the number of threads that can be blocked in system calls on behalf of Go code; those do not count against the GOMAXPROCS limit.

    The rest is up to the runtime, and is implementation (and version) specific. There are also probably more goroutines running than you may realize; see What are the three background goroutines in a Go program?

    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题