├── go.mod ├── platform_darwin.go ├── platform_linux.go ├── .gitignore ├── README.md ├── .github └── workflows │ └── mkill.yml ├── LICENSE ├── mkill_test.go └── mkill.go /go.mod: -------------------------------------------------------------------------------- 1 | module golang.design/x/mkill 2 | 3 | go 1.13 4 | -------------------------------------------------------------------------------- /platform_darwin.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The golang.design Initiative authors. 2 | // All rights reserved. Use of this source code is governed 3 | // by a MIT license that can be found in the LICENSE file. 4 | 5 | // +build darwin 6 | 7 | package mkill 8 | 9 | import "fmt" 10 | 11 | var cmdThreads = fmt.Sprintf("ps M %d | wc -l", pid) 12 | -------------------------------------------------------------------------------- /platform_linux.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The golang.design Initiative authors. 2 | // All rights reserved. Use of this source code is governed 3 | // by a MIT license that can be found in the LICENSE file. 4 | 5 | // +build linux 6 | 7 | package mkill 8 | 9 | import "fmt" 10 | 11 | var cmdThreads = fmt.Sprintf("ps hH p %d | wc -l", pid) 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mkill 2 | 3 | [![PkgGoDev](https://pkg.go.dev/badge/golang.design/x/mkill)](https://pkg.go.dev/golang.design/x/mkill) [![Go Report Card](https://goreportcard.com/badge/golang.design/x/mkill)](https://goreportcard.com/report/golang.design/x/mkill) 4 | ![mkill](https://github.com/golang-design/mkill/workflows/mkill/badge.svg?branch=master) 5 | 6 | Package mkill limits the number of threads in a Go program, without crash the whole program. 7 | 8 | ``` 9 | import "golang.design/x/mkill" 10 | ``` 11 | 12 | ## Quick Start 13 | 14 | ``` 15 | mkill.GOMAXTHREADS(10) 16 | ``` 17 | 18 | ## License 19 | 20 | MIT © The [golang.design](https://golang.design) Authors -------------------------------------------------------------------------------- /.github/workflows/mkill.yml: -------------------------------------------------------------------------------- 1 | name: mkill 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | 11 | build: 12 | name: Build 13 | runs-on: ubuntu-latest 14 | steps: 15 | 16 | - name: Set up Go 1.x 17 | uses: actions/setup-go@v2 18 | with: 19 | go-version: ^1.13 20 | id: go 21 | 22 | - name: Check out code into the Go module directory 23 | uses: actions/checkout@v2 24 | 25 | - name: Get dependencies 26 | run: | 27 | go get -v -t -d ./... 28 | 29 | - name: Test 30 | run: | 31 | go test -v -coverprofile=coverage.txt -covermode=atomic ./... 32 | 33 | - name: Upload coverage profile 34 | uses: codecov/codecov-action@v1 35 | with: 36 | token: ${{secrets.CODECOV_TOKEN}} 37 | file: coverage.txt -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 The golang.design Authors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /mkill_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The golang.design Initiative authors. 2 | // All rights reserved. Use of this source code is governed 3 | // by a MIT license that can be found in the LICENSE file. 4 | 5 | package mkill_test 6 | 7 | import ( 8 | "context" 9 | "fmt" 10 | "runtime" 11 | "sync" 12 | "testing" 13 | "time" 14 | 15 | "golang.design/x/mkill" 16 | ) 17 | 18 | func TestMKill(t *testing.T) { 19 | mkill.GOMAXTHREADS(10) 20 | 21 | // create a lot of threads by sleep gs 22 | wg := sync.WaitGroup{} 23 | wg.Add(100000) 24 | for i := 0; i < 100000; i++ { 25 | go func() { 26 | time.Sleep(time.Second * 1) 27 | wg.Done() 28 | }() 29 | } 30 | 31 | ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) 32 | defer cancel() 33 | ok := mkill.Wait(ctx) 34 | if !ok { 35 | t.Fatal("mkill failed in 10s") 36 | } 37 | wg.Wait() 38 | } 39 | 40 | func TestMinThreads(t *testing.T) { 41 | old := mkill.GOMAXTHREADS(0) 42 | n := runtime.NumCPU() 43 | if mkill.GOMAXTHREADS(n-1) != old { 44 | t.Fatalf("number of threads is less than required in the runtime") 45 | } 46 | } 47 | 48 | func ExampleGOMAXTHREADS() { 49 | mkill.GOMAXTHREADS(10) 50 | // Output: 51 | } 52 | 53 | func ExampleNumM() { 54 | mkill.GOMAXTHREADS(10) 55 | mkill.Wait(context.Background()) 56 | fmt.Println(mkill.NumM() <= 10) 57 | // Output: 58 | // true 59 | } 60 | 61 | func ExampleWait() { 62 | mkill.GOMAXTHREADS(10) 63 | 64 | ctx, cancel := context.WithTimeout(context.Background(), time.Second*100) 65 | defer cancel() 66 | fmt.Println(mkill.Wait(ctx)) 67 | // Output: 68 | // true 69 | } 70 | -------------------------------------------------------------------------------- /mkill.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The golang.design Initiative authors. 2 | // All rights reserved. Use of this source code is governed 3 | // by a MIT license that can be found in the LICENSE file. 4 | 5 | // Package mkill limits the number of threads in a Go program, without crash the whole program. 6 | package mkill // import "golang.design/x/mkill" 7 | 8 | import ( 9 | "context" 10 | "fmt" 11 | "os" 12 | "os/exec" 13 | "runtime" 14 | "strconv" 15 | "strings" 16 | "sync" 17 | "sync/atomic" 18 | "time" 19 | ) 20 | 21 | var ( 22 | pid = os.Getpid() 23 | minThreads = int32(runtime.NumCPU()) + 2 // minimum number of threads required by the runtime 24 | maxThreads = int32(runtime.NumCPU()) + 2 // 2 meaning runtime sysmon thread + template thread 25 | interval = time.Second 26 | debug = false 27 | ) 28 | 29 | // NumM returns the number of running threads. 30 | func NumM() int { 31 | out, err := exec.Command("bash", "-c", cmdThreads).Output() 32 | if err != nil && debug { 33 | fmt.Printf("mkill: failed to fetch #threads: %v\n", err) 34 | return 0 35 | } 36 | n, err := strconv.Atoi(strings.TrimSpace(string(out))) 37 | if err != nil && debug { 38 | fmt.Printf("mkill: failed to parse #threads: %v\n", err) 39 | return 0 40 | } 41 | return n 42 | } 43 | 44 | // GOMAXTHREADS sets the maximum number of system threads that allowed in a Go program 45 | // and returns the previous setting. If n is lower than minimum required number of threads, 46 | // it does not change the current setting. 47 | // The minimum allowed number of threads of a program is runtime.NumCPU() + 2. 48 | func GOMAXTHREADS(n int) int { 49 | if n < int(minThreads) { 50 | return int(atomic.LoadInt32(&maxThreads)) 51 | } 52 | 53 | return int(atomic.SwapInt32(&maxThreads, int32(n))) 54 | } 55 | 56 | // Wait waits until the number of threads meet the GOMAXTHREADS settings. 57 | // The function always returns true if the ctx is not canceled. 58 | // Otherwise returns true only if the Wait is successed in the last check. 59 | func Wait(ctx context.Context) (ok bool) { 60 | for { 61 | select { 62 | case <-ctx.Done(): 63 | if NumM() <= GOMAXTHREADS(0) { 64 | ok = true 65 | } 66 | return 67 | default: 68 | if NumM() > GOMAXTHREADS(0) { 69 | continue 70 | } 71 | ok = true 72 | return 73 | } 74 | } 75 | } 76 | 77 | func checkwork() { 78 | _, err := exec.Command("bash", "-c", cmdThreads).Output() 79 | if err != nil { 80 | panic(fmt.Sprintf("mkill: failed to use the package: %v", err)) 81 | } 82 | } 83 | 84 | func init() { 85 | checkwork() 86 | if debug { 87 | fmt.Printf("mkill: pid %v, maxThread %v, interval %v\n", pid, maxThreads, interval) 88 | } 89 | 90 | wg := sync.WaitGroup{} 91 | go func() { 92 | t := time.NewTicker(interval) 93 | for { 94 | select { 95 | case <-t.C: 96 | n := NumM() 97 | nkill := int32(n) - atomic.LoadInt32(&maxThreads) 98 | if nkill <= 0 { 99 | if debug { 100 | fmt.Printf("mkill: checked #threads total %v / max %v\n", n, maxThreads) 101 | } 102 | continue 103 | } 104 | wg.Add(int(nkill)) 105 | for i := int32(0); i < nkill; i++ { 106 | go func() { 107 | runtime.LockOSThread() 108 | wg.Done() 109 | }() 110 | } 111 | wg.Wait() 112 | if debug { 113 | fmt.Printf("mkill: killing #threads, remaining: %v\n", n) 114 | } 115 | } 116 | } 117 | }() 118 | } 119 | --------------------------------------------------------------------------------