|
| 1 | +package mkill |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "os/exec" |
| 7 | + "runtime" |
| 8 | + "strconv" |
| 9 | + "strings" |
| 10 | + "sync/atomic" |
| 11 | + "time" |
| 12 | +) |
| 13 | + |
| 14 | +var ( |
| 15 | + pid = os.Getpid() |
| 16 | + maxThread = int32(runtime.NumCPU()) |
| 17 | + interval = time.Second |
| 18 | + debug = true |
| 19 | +) |
| 20 | + |
| 21 | +func checkwork() { |
| 22 | + _, err := getThreads() |
| 23 | + if err != nil { |
| 24 | + panic(fmt.Sprintf("mkill: failed to use the library: %v", err)) |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +func init() { |
| 29 | + checkwork() |
| 30 | + |
| 31 | + if debug { |
| 32 | + fmt.Printf("mkill: pid %v, maxThread %v, interval %v\n", pid, maxThread, interval) |
| 33 | + } |
| 34 | + go func() { |
| 35 | + t := time.NewTicker(interval) |
| 36 | + for { |
| 37 | + select { |
| 38 | + case <-t.C: |
| 39 | + n, _ := getThreads() |
| 40 | + nkill := int32(n) - atomic.LoadInt32(&maxThread) |
| 41 | + if nkill <= 0 { |
| 42 | + if debug { |
| 43 | + fmt.Printf("mkill: checked #threads total %v / max %v\n", n, maxThread) |
| 44 | + } |
| 45 | + continue |
| 46 | + } |
| 47 | + for i := int32(0); i < nkill; i++ { |
| 48 | + go func() { |
| 49 | + runtime.LockOSThread() |
| 50 | + }() |
| 51 | + } |
| 52 | + if debug { |
| 53 | + fmt.Printf("mkill: killing #threads, remaining: %v\n", n) |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + }() |
| 58 | +} |
| 59 | + |
| 60 | +// GOMAXTHREADS change the limites of the maximum threads in runtime |
| 61 | +// and returns the previous number of threads limit |
| 62 | +func GOMAXTHREADS(n int) int { |
| 63 | + return int(atomic.SwapInt32(&maxThread, int32(n))) |
| 64 | +} |
| 65 | + |
| 66 | +// getThreads returns the number of running threads |
| 67 | +// Linux: |
| 68 | +func getThreads() (int, error) { |
| 69 | + out, err := exec.Command("bash", "-c", cmdThreads).Output() |
| 70 | + if err != nil { |
| 71 | + return 0, fmt.Errorf("mkill: failed to fetch #threads: %v", err) |
| 72 | + } |
| 73 | + n, err := strconv.Atoi(strings.TrimSpace(string(out))) |
| 74 | + if err != nil { |
| 75 | + return 0, fmt.Errorf("mkill: failed to parse #threads: %v", err) |
| 76 | + } |
| 77 | + return n, nil |
| 78 | +} |
0 commit comments