golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
124.03k stars 17.67k forks source link

runtime/cgo: Assign a thread name for C-created threads #47909

Open antJack opened 3 years ago

antJack commented 3 years ago

What version of Go are you using (go version)?

$ go version
go version go1.14.13 linux/amd64

Does this issue reproduce with the latest release?

yes

What did you do?

Profiling an embedding Go program. That is, calling go functions from C++ environment through cgo.

However, when I tried to profile my program with perf (since pprof cannot provide as much info about C++ as perf), I found that some of the executions of Go worker pool were laid on a C++ thread, as shown in the left part of the screenshot. It confused me why those worker pool codes ran on my C++ thread and did waste a lot of time.

Finally, I found that the newly created thread shares the same thread name as its father, i.e., the C++ worker thread, which causes the perf to draw the Go part on C++ worker thread.

image

The execution path is:

runtime.main 
-> startTemplateThread 
-> newm
-> newm1 
-> _cgo_thread_start 
-> x_cgo_thread_start 
-> _cgo_sys_thread_start 
-> _cgo_try_pthread_create 
-> pthread_create

And the newly created thread inherits the thread name from its parent thread, and that causes the flame graph to misbehave as shown above. The solution to this problem is also simple: call _pthread_setnamenp just after the creation of new thread.

What did you expect to see?

The newly created cgo template thread should use a different thread name from its parent.

What did you see instead?

cgo template thread uses the same thread name as its parent, which causes misleading when perf-ing the program.

ianlancetaylor commented 3 years ago

Any suggestions as to what the thread name should be?