Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add sysutil #523

Merged
merged 1 commit into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions sysutil/sysutil.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package sysutil

import (
"runtime/debug"
)

// SetMaxThreads sets the maximum number of operating system
// threads that the Go program can use. If it attempts to use more than
// this many, the program crashes.
// SetMaxThreads returns the previous setting.
// The initial setting is 10,000 threads.
//
// The limit controls the number of operating system threads, not the number
// of goroutines. A Go program creates a new thread only when a goroutine
// is ready to run but all the existing threads are blocked in system calls, cgo calls,
// or are locked to other goroutines due to use of runtime.LockOSThread.
//
// SetMaxThreads is useful mainly for limiting the damage done by
// programs that create an unbounded number of threads. The idea is
// to take down the program before it takes down the operating system.
func SetMaxThreads(threads int) int {
return debug.SetMaxThreads(threads)
}
20 changes: 20 additions & 0 deletions sysutil/sysutil_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package sysutil

import (
"runtime/debug"
"testing"

"github.com/stretchr/testify/require"
)

func TestSetMaxThreads(t *testing.T) {
originalMaxThreads := debug.SetMaxThreads(10000)
defer debug.SetMaxThreads(originalMaxThreads)

newMaxThreads := 5000
previousMaxThreads := SetMaxThreads(newMaxThreads)
require.Equal(t, 10000, previousMaxThreads, "Expected previous max threads to be 10000")
require.Equal(t, newMaxThreads, debug.SetMaxThreads(newMaxThreads), "Expected max threads to be set to 5000")

SetMaxThreads(originalMaxThreads)
}
Loading