github.com/4ad/go@v0.0.0-20161219182952-69a12818b605/src/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 static int cpuHogThreadCount; 34 35 struct cgoTracebackArg { 36 uintptr_t context; 37 uintptr_t sigContext; 38 uintptr_t* buf; 39 uintptr_t max; 40 }; 41 42 static void *pprofThread(void* p) { 43 time_t start; 44 45 (void)p; 46 start = time(NULL); 47 while (__sync_add_and_fetch(&cpuHogThreadCount, 0) < 2 && time(NULL) - start < 2) { 48 cpuHogThread(); 49 } 50 } 51 52 53 // pprofCgoThreadTraceback is passed to runtime.SetCgoTraceback. 54 // For testing purposes it pretends that all CPU hits in C code are in cpuHog. 55 void pprofCgoThreadTraceback(void* parg) { 56 struct cgoTracebackArg* arg = (struct cgoTracebackArg*)(parg); 57 arg->buf[0] = (uintptr_t)(cpuHogThread) + 0x10; 58 arg->buf[1] = 0; 59 __sync_add_and_fetch(&cpuHogThreadCount, 1); 60 } 61 62 // getCPUHogThreadCount fetches the number of times we've seen cpuHogThread 63 // in the traceback. 64 int getCPUHogThreadCount() { 65 return __sync_add_and_fetch(&cpuHogThreadCount, 0); 66 } 67 */ 68 import "C" 69 70 import ( 71 "fmt" 72 "io/ioutil" 73 "os" 74 "runtime" 75 "runtime/pprof" 76 "time" 77 "unsafe" 78 ) 79 80 func init() { 81 register("CgoPprofThread", CgoPprofThread) 82 } 83 84 func CgoPprofThread() { 85 runtime.SetCgoTraceback(0, unsafe.Pointer(C.pprofCgoThreadTraceback), nil, nil) 86 87 f, err := ioutil.TempFile("", "prof") 88 if err != nil { 89 fmt.Fprintln(os.Stderr, err) 90 os.Exit(2) 91 } 92 93 if err := pprof.StartCPUProfile(f); err != nil { 94 fmt.Fprintln(os.Stderr, err) 95 os.Exit(2) 96 } 97 98 t0 := time.Now() 99 for C.getCPUHogThreadCount() < 2 && time.Since(t0) < time.Second { 100 time.Sleep(100 * time.Millisecond) 101 } 102 103 pprof.StopCPUProfile() 104 105 name := f.Name() 106 if err := f.Close(); err != nil { 107 fmt.Fprintln(os.Stderr, err) 108 os.Exit(2) 109 } 110 111 fmt.Println(name) 112 }