Skip to content

Commit 79fa893

Browse files
authored
Merge pull request #523 from projectdiscovery/add_sysutil
add sysutil
2 parents eeccea1 + f282164 commit 79fa893

2 files changed

Lines changed: 43 additions & 0 deletions

File tree

sysutil/sysutil.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package sysutil
2+
3+
import (
4+
"runtime/debug"
5+
)
6+
7+
// SetMaxThreads sets the maximum number of operating system
8+
// threads that the Go program can use. If it attempts to use more than
9+
// this many, the program crashes.
10+
// SetMaxThreads returns the previous setting.
11+
// The initial setting is 10,000 threads.
12+
//
13+
// The limit controls the number of operating system threads, not the number
14+
// of goroutines. A Go program creates a new thread only when a goroutine
15+
// is ready to run but all the existing threads are blocked in system calls, cgo calls,
16+
// or are locked to other goroutines due to use of runtime.LockOSThread.
17+
//
18+
// SetMaxThreads is useful mainly for limiting the damage done by
19+
// programs that create an unbounded number of threads. The idea is
20+
// to take down the program before it takes down the operating system.
21+
func SetMaxThreads(threads int) int {
22+
return debug.SetMaxThreads(threads)
23+
}

sysutil/sysutil_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package sysutil
2+
3+
import (
4+
"runtime/debug"
5+
"testing"
6+
7+
"github.com/stretchr/testify/require"
8+
)
9+
10+
func TestSetMaxThreads(t *testing.T) {
11+
originalMaxThreads := debug.SetMaxThreads(10000)
12+
defer debug.SetMaxThreads(originalMaxThreads)
13+
14+
newMaxThreads := 5000
15+
previousMaxThreads := SetMaxThreads(newMaxThreads)
16+
require.Equal(t, 10000, previousMaxThreads, "Expected previous max threads to be 10000")
17+
require.Equal(t, newMaxThreads, debug.SetMaxThreads(newMaxThreads), "Expected max threads to be set to 5000")
18+
19+
SetMaxThreads(originalMaxThreads)
20+
}

0 commit comments

Comments
 (0)