github.com/geraldss/go/src@v0.0.0-20210511222824-ac7d0ebfc235/runtime/testdata/testprogcgo/threadpprof.go (about) 1 // Copyright 2016 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // +build !plan9,!windows 6 7 package main 8 9 // Run a slow C function saving a CPU profile. 10 11 /* 12 #include <stdint.h> 13 #include <time.h> 14 #include <pthread.h> 15 16 int threadSalt1; 17 int threadSalt2; 18 19 void cpuHogThread() { 20 int foo = threadSalt1; 21 int i; 22 23 for (i = 0; i < 100000; i++) { 24 if (foo > 0) { 25 foo *= foo; 26 } else { 27 foo *= foo + 1; 28 } 29 } 30 threadSalt2 = foo; 31 } 32 33 void cpuHogThread2() { 34 } 35 36 static int cpuHogThreadCount; 37 38 struct cgoTracebackArg { 39 uintptr_t context; 40 uintptr_t sigContext; 41 uintptr_t* buf; 42 uintptr_t max; 43 }; 44 45 // pprofCgoThreadTraceback is passed to runtime.SetCgoTraceback. 46 // For testing purposes it pretends that all CPU hits in C code are in cpuHog. 47 void pprofCgoThreadTraceback(void* parg) { 48 struct cgoTracebackArg* arg = (struct cgoTracebackArg*)(parg); 49 arg->buf[0] = (uintptr_t)(cpuHogThread) + 0x10; 50 arg->buf[1] = (uintptr_t)(cpuHogThread2) + 0x4; 51 arg->buf[2] = 0; 52 __sync_add_and_fetch(&cpuHogThreadCount, 1); 53 } 54 55 // getCPUHogThreadCount fetches the number of times we've seen cpuHogThread 56 // in the traceback. 57 int getCPUHogThreadCount() { 58 return __sync_add_and_fetch(&cpuHogThreadCount, 0); 59 } 60 61 static void* cpuHogDriver(void* arg __attribute__ ((unused))) { 62 while (1) { 63 cpuHogThread(); 64 } 65 return 0; 66 } 67 68 void runCPUHogThread(void) { 69 pthread_t tid; 70 pthread_create(&tid, 0, cpuHogDriver, 0); 71 } 72 */ 73 import "C" 74 75 import ( 76 "fmt" 77 "os" 78 "runtime" 79 "runtime/pprof" 80 "time" 81 "unsafe" 82 ) 83 84 func init() { 85 register("CgoPprofThread", CgoPprofThread) 86 register("CgoPprofThreadNoTraceback", CgoPprofThreadNoTraceback) 87 } 88 89 func CgoPprofThread() { 90 runtime.SetCgoTraceback(0, unsafe.Pointer(C.pprofCgoThreadTraceback), nil, nil) 91 pprofThread() 92 } 93 94 func CgoPprofThreadNoTraceback() { 95 pprofThread() 96 } 97 98 func pprofThread() { 99 f, err := os.CreateTemp("", "prof") 100 if err != nil { 101 fmt.Fprintln(os.Stderr, err) 102 os.Exit(2) 103 } 104 105 if err := pprof.StartCPUProfile(f); err != nil { 106 fmt.Fprintln(os.Stderr, err) 107 os.Exit(2) 108 } 109 110 C.runCPUHogThread() 111 112 t0 := time.Now() 113 for C.getCPUHogThreadCount() < 2 && time.Since(t0) < time.Second { 114 time.Sleep(100 * time.Millisecond) 115 } 116 117 pprof.StopCPUProfile() 118 119 name := f.Name() 120 if err := f.Close(); err != nil { 121 fmt.Fprintln(os.Stderr, err) 122 os.Exit(2) 123 } 124 125 fmt.Println(name) 126 }