trace tool showing goroutines moving between procs after LockOSThread

145 views
Skip to first unread message

Miki Tebeka

unread,
Oct 6, 2019, 7:47:43 AM10/6/19
to golang-nuts
Hi,

I'm trying to understand output of the "go tool trace". I'm using runtime.LockOSThread, however the output of the trace tool shows goroutines moving between procs (which I *think* are OS threads). What am I missing?

Code:
package main

import (
"fmt"
"os"
"runtime"
"runtime/trace"
"time"
)

func sqrt(val float64) (float64, error) {
if val < 0.0 {
return 0.0, fmt.Errorf("sqrt of negative number")
}

if val == 0.0 {
return 0.0, nil // shortcut
}

guess, epsilon := 1.0, 0.00001
for i := 0; i < 10000; i++ {
diff := guess*guess - val
if diff < 0 {
diff = -diff
}
if diff <= epsilon {
return guess, nil
}
guess = (val/guess + guess) / 2.0
}

return 0.0, fmt.Errorf("can't find sqrt of %f", val)
}

func worker(id int) {
runtime.LockOSThread()
i := float64(0)
for {
for n := 0; n < 1000000; n++ {
i += 13.2
_, err := sqrt(i)
if err != nil {
panic(err)
}
}
runtime.Gosched()
}
}

func main() {
out, err := os.Create("trace.out")
if err != nil {
panic(err)
}
defer out.Close()
if err := trace.Start(out); err != nil {
panic(err)
}
defer trace.Stop()

for i := 0; i < runtime.NumCPU(); i++ {
go worker(i)
}

time.Sleep(3 * time.Second)
}


What I see in trace:

trace-out.png


Thanks,
Miki

Chris Hines

unread,
Oct 7, 2019, 1:40:22 PM10/7/19
to golang-nuts
I am pretty sure that a "proc" in the trace visualization output is the same as a "P" in the parlance of the Go runtime scheduler. In the scheduler an OS thread is an "M" and even when using LockOSThread the locked goroutine and thread need to be paired up with one of the scheduler's Ps in order to execute the goroutine's code. There are always GOMAXPROCS # of Ps in the scheduler. See the comment block starting at line 19 in this code for more detail. https://golang.org/src/runtime/proc.go

Hope that helps,
Chris

Miki Tebeka

unread,
Oct 22, 2019, 2:07:10 AM10/22/19
to golang-nuts
Thanks Chris
Reply all
Reply to author
Forward
0 new messages