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:
- In Program 1 what are these 2 threads. I guess one is for "main", but what is the other one for?
- 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.